【发布时间】:2012-09-20 03:46:32
【问题描述】:
我在一个对象上调用 user.save(),我在其中设置了 user.signup_date = null;
user.first_name = null;
user.signup_date = null;
user.save();
但是当我在 mongodb 中查看用户时,它仍然设置了 signup_date 和 first_name...如何有效地将此字段设置为空或 null?
【问题讨论】:
我在一个对象上调用 user.save(),我在其中设置了 user.signup_date = null;
user.first_name = null;
user.signup_date = null;
user.save();
但是当我在 mongodb 中查看用户时,它仍然设置了 signup_date 和 first_name...如何有效地将此字段设置为空或 null?
【问题讨论】:
要从现有文档中删除这些属性,请在保存文档之前将它们设置为 undefined 而不是 null:
user.first_name = undefined;
user.signup_date = undefined;
user.save();
确认仍在 Mongoose 5.9.7 中工作。请注意,您尝试删除的字段仍必须在您的架构中定义才能正常工作。
【讨论】:
如果您尝试使用 set 方法是否会有所不同,如下所示:
user.set('first_name', null);
user.set('signup_date', null);
user.save();
或者可能是保存的时候出错了,如果这样做会发生什么:
user.save(function (err) {
if (err) console.log(err);
});
它会在日志中打印任何内容吗?
【讨论】:
另一种选择是将这些属性的默认值定义为undefined。
类似于以下内容:
let userSchema = new mongoose.Schema({
first_name: {
type: String,
default: undefined
},
signup_date: {
type: Date,
default: undefined
}
})
【讨论】:
只需删除字段
delete user.first_name;
delete user.signup_date;
user.save();
【讨论】:
user = user.toObject()。
在Mongoose documentation(架构类型)上,您可以转到Arrays 的说明。在那里,它说:
数组是特殊的,因为它们隐含的默认值为
[](空数组)。
var ToyBox = mongoose.model('ToyBox', ToyBoxSchema);
console.log((new ToyBox()).toys); // []
要覆盖此默认值,您需要将
default值设置为undefined
(我在 toys 元素中添加了一个内容)
var ToyBoxSchema = new Schema({
toys: {
type: [{
name: String,
features: [String]
}],
default: undefined
}
});
【讨论】: