使用Mongoose从MongoDB文档中删除键
-
11-10-2019 - |
题
我正在使用 猫鼬 用于使用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();
});
解决方案
在早期版本中,您将需要删除节点蒙哥多本地驱动程序。每个模型都有一个集合对象,其中包含Node-MongoDB本地提供的所有方法。因此,您可以通过此操作:
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);
其他提示
您要这样做:
User.findOne({}, function(err, user){
user.key_to_delete = undefined;
user.save();
});
我使用Mongoose,并使用上述任何功能为我提供了要求。该函数无编译错误,但该字段仍将保留。
user.set('key_to_delete', undefined, {strict: false} );
为我做了诀窍。
这可能是一个副问题,例如使用
function (user)
代替
function(err, user)
对于发现的回调?就像我已经发生的情况一样,只是试图帮助这一点。
Mongoose文档不是一个普通的JavaScript对象,这就是为什么您不能使用删除操作员(或 unset
来自“ Lodash”库)。
您的选项是设置doc.path = null ||未定义或使用document.toObject()方法将mongoose doc转换为普通对象,并从那里照常使用。阅读更多信息: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
});
所有这些答案的问题在于它们在一个领域工作。例如,假设我要删除文档中的所有字段,如果它们是一个空字符串 ""
。首先,您应该检查字段是否为空字符串将其放在 $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 },
);
}
如果要从集合中删除键,请尝试此方法。 这对我有用
db.getCollection('myDatabaseTestCollectionName').update({"FieldToDelete": {$exists: true}}, {$unset:{"FieldToDelete":1}}, false, true);
您可以使用delete user._doc.key
不隶属于 StackOverflow