我正在使用 Mongoose使用 node.js 访问 MongoDB 的库
有没有办法从文档中删除 key ?即不只是将值设置为 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();
});
最佳答案
在早期版本中,您需要下拉 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);
https://stackoverflow.com/questions/4486926/