使用Mongoose从MongoDB文档中删除密钥 [英] Delete a key from a MongoDB document using Mongoose

查看:73
本文介绍了使用Mongoose从MongoDB文档中删除密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

是否可以从文档中删除密钥?即不只是将值设置为null,而是将其删除?

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

推荐答案

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

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

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

Since version 2.0 you can do:

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

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

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

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

这篇关于使用Mongoose从MongoDB文档中删除密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆