我遇到了一个有趣的问题,试图用 mongoose 将 mongo 中子数组的一个元素设置为 null(是的,这看起来非常明显)。
我的架构看起来像:
var ItemSchema = new Schema({
name : String,
slots: { type: [{ type : Schema.Types.ObjectId, ref: 'Slot' }], default: [] }
});
我的数据看起来像:
{
_id : ObjectId("53bafbfd00cbcc3a1178e11b"),
name : "item 1",
slots: [null, null, ObjectId("53baf297d63228631029d2f8"), null, null]
},
{
_id : ObjectId("53baf297d63228631029d2f8"),
name : "item 2",
slots: [ObjectId("53baf1b3fecfe25c10233801"), null, null, null, null]
}
注意:null
值对于顺序逻辑目的很重要。
那么,假设我得到了这些元素中的第一个:
Items.findById('53bafbfd00cbcc3a1178e11b', function (err, item) {
console.log(item.slots);
// [null, null, "53baf297d63228631029d2f8", null, null] --> OK
// BIG update here
item.slots[2] = null;
item.save(function (err, itemSaved) {
// no errors
console.log(itemSaved.slots);
// [null, null, null, null, null] --> Well, so everything works, right ?
// so let's find the same item again !
Items.findById('53bafbfd00cbcc3a1178e11b', function (err, itemSearched) {
console.log(itemSearched.slots);
// [null, null, "53baf297d63228631029d2f8", null, null] --> what ?? id still here ?
});
});
});
因此,即使 save
有效,id 也不会设置为 null
。我真的不明白。我非常需要一个解释!提前致谢。
最佳答案
看来您需要将该元素显式标记为已修改,否则保存
不会获取更改:
item.slots[2] = null;
item.markModified('slots.2');
item.save(function (err, itemSaved) {
....
可能是因为 null
不是有效的 ObjectId
。
另一种方法是使用 update
和 $unset
:
Items.update(
{_id: '53bafbfd00cbcc3a1178e11b'},
{$unset: {'slots.2': 1}}, function(err, numAffected) {
...
关于node.js - 使用 Mongoose 将数组元素设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24619384/