node.js 使用 mongoose 将 mongo 对象的字段设置为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12636938/
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
set field as empty for mongo object using mongoose
提问by chovy
I'm calling user.save() on an object, where I set user.signup_date = null;
我在一个对象上调用 user.save(),在那里我设置了 user.signup_date = null;
user.first_name = null;
user.signup_date = null;
user.save();
But when I look at the user in the mongodb it still has the signup_date and first_name set...how do I effectively set this field as empty or null?
但是当我查看 mongodb 中的用户时,它仍然设置了 signup_date 和 first_name ......我如何有效地将此字段设置为空或空?
回答by JohnnyHK
To remove those properties from your existing doc, set them to undefinedinstead of nullbefore saving the doc:
要从现有文档中删除这些属性,请在保存文档之前将它们设置为undefined而不是null:
user.first_name = undefined;
user.signup_date = undefined;
user.save();
Confirmed as still working in Mongoose 5.9.7. Note that the field you're trying to remove must still be defined in your schema for this to work.
确认仍然在 Mongoose 5.9.7 中工作。请注意,您尝试删除的字段仍必须在您的架构中定义才能使其工作。
回答by joakimbeng
Does it make a difference if you try the set method instead, like this:
如果您尝试使用 set 方法,是否会有所不同,如下所示:
user.set('first_name', null);
user.set('signup_date', null);
user.save();
Or maybe there's an error when saving, what happens if you do:
或者保存时可能出现错误,如果您这样做会发生什么:
user.save(function (err) {
if (err) console.log(err);
});
Does it print anything to the log?
它会在日志中打印任何内容吗?
回答by Kfir Erez
Another option is to define a default value as undefinedfor these properties.
另一种选择是undefined为这些属性定义默认值。
Something like the following:
类似于以下内容:
let userSchema = new mongoose.Schema({
first_name: {
type: String,
default: undefined
},
signup_date: {
type: Date,
default: undefined
}
})
let userSchema = new mongoose.Schema({
first_name: {
type: String,
default: undefined
},
signup_date: {
type: Date,
default: undefined
}
})
回答by Guillem
On Mongoose documentation(Schema Types), you can go to the Arraysexplanation. There, it says this:
在Mongoose 文档(Schema Types)上,你可以去Arrays解释。在那里,它说:
Arrays are special because they implicitly have a default value of
[](empty array).
数组是特殊的,因为它们隐式具有
[](空数组)的默认值。
var ToyBox = mongoose.model('ToyBox', ToyBoxSchema);
console.log((new ToyBox()).toys); // []
To overwrite this default, you need to set the
defaultvalue toundefined
要覆盖此默认值,您需要将该
default值设置为undefined
(I've made an addition inside the toyselement)
(我在toys元素内部做了一个添加)
var ToyBoxSchema = new Schema({
toys: {
type: [{
name: String,
features: [String]
}],
default: undefined
}
});
回答by PierrickP
Just delete fields
只需删除字段
delete user.first_name;
delete user.signup_date;
user.save();

