使用 Mongoose 从 MongoDB 文档中删除键

发布于 2024-10-08 02:21:49 字数 433 浏览 5 评论 0原文

我正在使用 Mongoose 库通过 node.js 访问 MongoDB

有没有办法删除文档中的密钥?即不只是将值设置为 null,而是将其删除?

User.findOne({}, function(err, user){
  //correctly sets the key to null... but it's still present in the document
  user.key_to_delete = null;

  // doesn't seem to have any effect
  delete user.key_to_delete;

  user.save();
});

I'm using the Mongoose Library for accessing MongoDB with node.js

Is there a way to remove a key from a document? i.e. not just set the value to null, but remove it?

User.findOne({}, function(err, user){
  //correctly sets the key to null... but it's still present in the document
  user.key_to_delete = null;

  // doesn't seem to have any effect
  delete user.key_to_delete;

  user.save();
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

隐诗 2024-10-15 02:21:49

在早期版本中,您需要下拉 node-mongodb-native 驱动程序。每个模型都有一个集合对象,其中包含node-mongodb-native 提供的所有方法。因此,您可以通过以下方式执行相关操作:

User.collection.update({_id: user._id}, {$unset: {field: 1 }});

从版本 2.0 开始,您可以执行以下操作:

User.update({_id: user._id}, {$unset: {field: 1 }}, callback);

从版本 2.4 开始,如果您已经有模型实例,则可以执行以下操作:

doc.field = undefined;
doc.save(callback);

In early versions, you would have needed to drop down the node-mongodb-native driver. Each model has a collection object that contains all the methods that node-mongodb-native offers. So you can do the action in question by this:

User.collection.update({_id: user._id}, {$unset: {field: 1 }});

Since version 2.0 you can do:

User.update({_id: user._id}, {$unset: {field: 1 }}, callback);

And since version 2.4, if you have an instance of a model already you can do:

doc.field = undefined;
doc.save(callback);
迟到的我 2024-10-15 02:21:49

你会想要这样做:

User.findOne({}, function(err, user){
  user.key_to_delete = undefined;
  user.save();
});

You'll want to do this:

User.findOne({}, function(err, user){
  user.key_to_delete = undefined;
  user.save();
});
薔薇婲 2024-10-15 02:21:49

我使用猫鼬并使用上述任何功能满足了我的要求。该函数编译时没有错误,但该字段仍然保留。

user.set('key_to_delete', undefined, {strict: false} );

为我成功了。

I use mongoose and using any of the above functions did me the requirement. The function compiles error free but the field would still remain.

user.set('key_to_delete', undefined, {strict: false} );

did the trick for me.

皇甫轩 2024-10-15 02:21:49

在 mongo 语法中,要删除某些键,您需要执行以下操作:

{ $unset : { field : 1} }

在 Mongoose 中似乎也是如此。

编辑

检查示例。

At mongo syntax to delete some key you need do following:

{ $unset : { field : 1} }

Seems at Mongoose the same.

Edit

Check this example.

木格 2024-10-15 02:21:49

如果您想从集合中删除密钥,请尝试此方法。

 db.getCollection('myDatabaseTestCollectionName').update({"FieldToDelete": {$exists: true}}, {$unset:{"FieldToDelete":1}}, false, true);

if you want to remove a key from collection try this method.

 db.getCollection('myDatabaseTestCollectionName').update({"FieldToDelete": {$exists: true}}, {$unset:{"FieldToDelete":1}}, false, true);
地狱即天堂 2024-10-15 02:21:49

尝试:

User.findOne({}, function(err, user){
  // user.key_to_delete = null; X
  `user.key_to_delete = undefined;`

  delete user.key_to_delete;

  user.save();
});

Try:

User.findOne({}, function(err, user){
  // user.key_to_delete = null; X
  `user.key_to_delete = undefined;`

  delete user.key_to_delete;

  user.save();
});
好多鱼好多余 2024-10-15 02:21:49

这可能是一个附带问题,例如使用

function (user)

而不是

function(err, user)

查找的回调吗?只是想帮忙解决这个问题,因为我已经遇到过这种情况。

Could this be a side problem like using

function (user)

instead of

function(err, user)

for the find's callback ? Just trying to help with this as I already had the case.

美煞众生 2024-10-15 02:21:49

Mongoose 文档不是普通的 javascript 对象,这就是为什么您不能使用删除运算符。(或从“lodash”库中取消设置)。

您的选择是设置 doc.path = null || undefined 或使用 Document.toObject() 方法将 mongoose doc 转换为普通对象,然后像往常一样使用它。
在 mongoose api-ref 中阅读更多内容:
http://mongoosejs.com/docs/api.html#document_Document-toObject

示例如下所示:

User.findById(id, function(err, user) {
    if (err) return next(err);
    let userObject = user.toObject();
    // userObject is plain object
});

Mongoose document is NOT a plain javascript object and that's why you can't use delete operator.(Or unset from 'lodash' library).

Your options are to set doc.path = null || undefined or to use Document.toObject() method to turn mongoose doc to plain object and from there use it as usual.
Read more in mongoose api-ref:
http://mongoosejs.com/docs/api.html#document_Document-toObject

Example would look something like this:

User.findById(id, function(err, user) {
    if (err) return next(err);
    let userObject = user.toObject();
    // userObject is plain object
});
长途伴 2024-10-15 02:21:49

所有这些答案的问题在于它们只适用于一个领域。例如,假设我想删除文档中的所有字段(如果它们是空字符串 "")。
首先,您应该检查字段是否为空字符串,将其放入 $unset

function unsetEmptyFields(updateData) {
  const $unset = {};
  Object.keys(updatedData).forEach((key) => {
    if (!updatedData[key]) {
      $unset[key] = 1;
      delete updatedData[key];
    }
  });
  updatedData.$unset = $unset;

  if (isEmpty(updatedData.$unset)) { delete updatedData.$unset; }

  return updatedData;
}

function updateUserModel(data){
const updatedData = UnsetEmptyFiled(data);

    const Id = "";
    User.findOneAndUpdate(
      { _id: Id },
      updatedData, { new: true },
    );
}

the problem with all of these answers is that they work for one field. for example let's say i want delete all fields from my Document if they were an empty string "".
First you should check if field is empty string put it to $unset :

function unsetEmptyFields(updateData) {
  const $unset = {};
  Object.keys(updatedData).forEach((key) => {
    if (!updatedData[key]) {
      $unset[key] = 1;
      delete updatedData[key];
    }
  });
  updatedData.$unset = $unset;

  if (isEmpty(updatedData.$unset)) { delete updatedData.$unset; }

  return updatedData;
}

function updateUserModel(data){
const updatedData = UnsetEmptyFiled(data);

    const Id = "";
    User.findOneAndUpdate(
      { _id: Id },
      updatedData, { new: true },
    );
}

云仙小弟 2024-10-15 02:21:49

等待 yourModel.findByIdAndUpdate(
_ID,
{
$set:更新字段,
$未设置:{ fieldToDelete:1 }
},
{ 新: 真 }
);

await yourModel.findByIdAndUpdate(
_id,
{
$set: updateFields,
$unset: { fieldToDelete: 1 }
},
{ new: true }
);

暮光沉寂 2024-10-15 02:21:49

你可以使用
删除用户._doc.key

you can use
delete user._doc.key

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文