node.js 使用 Mongoose 从 MongoDB 文档中删除一个键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4486926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:46:43  来源:igfitidea点击:

Delete a key from a MongoDB document using Mongoose

mongodbnode.jsmongoosedocument-database

提问by Daniel Beardsley

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

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

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();
});

回答by staackuser2

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:

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

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

Since version 2.0 you can do:

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

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:

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

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

回答by deedubs

You'll want to do this:

你会想要这样做:

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

回答by Noushad

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.

帮我解决了这个问题。

回答by Andrew Orsich

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

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

{ $unset : { field : 1} }

Seems at Mongoose the same.

似乎在猫鼬一样。

Edit

编辑

Check thisexample.

检查这个例子。

回答by Luc

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.

对于 find 的回调?只是想帮助解决这个问题,因为我已经有了这个案例。

回答by petarr

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

Mongoose 文档不是普通的 javascript 对象,这就是您不能使用 delete 运算符的原因。(或unset来自“lodash”库)。

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

您的选择是设置 doc.path = null || undefined 或使用 Document.toObject() 方法将 mongoose doc 转换为普通对象,然后照常使用它。在 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
});

回答by Milad ranjbar

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:

所有这些答案的问题在于它们适用于一个领域。例如,假设我想从我的文档中删除所有字段,如果它们是空字符串""。首先,您应该检查字段是否为空字符串将其放入$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 },
    );
}

回答by Bivin Vinod

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

如果你想从集合中删除一个键,试试这个方法。这对我有用

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

回答by Jeisson Valderrama

Try:

尝试:

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

  delete user.key_to_delete;

  user.save();
});

回答by Joel Esperanza

you can use delete user._doc.key

您可以使用删除 user._doc.key