使用 Mongoose 从 MongoDB 文档中删除一个键 [英] Delete a key from a MongoDB document using Mongoose
问题描述
我正在使用 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屋!