如何使用$ push查询将数据插入到子文档中,而不是检索文档并将其保存回来
编辑:这实际上是工作
作为Mongoose – Subdocs:“Adding subdocs”文档说,我们可以使用push
方法添加一个subdoc(即parent.children.push({ name: 'Liesl' });
)
但我想走得更远,并希望使用$push
操作符来插入子文档。
我有两个Schema: ThingSchema
:
var ThingSchema = mongoose.Schema({ name: { type: String, required: true }, description: { type: String } });
和BoxSchema
,它是BoxSchema
的子文档( things
)数组的主文档:
var BoxSchema = new mongoose.Schema({ name: { type: String, required: true }, description: { type: String }, things: { type: [ThingSchema] } }); var BoxModel = mongoose.model('Box', BoxSchema);
我需要things
每个子文档具有unique
名称 – 也就是说,不可能将新文档插入到name
值已经存在于子文档中的数组中。
我正在尝试做类似的事情:
var thingObj = ... // the 'thing' object to be inserted BoxModel.update({ _id: some_box_id, // a valid 'box' ObjectId "things.name": { "$ne": thingObj.name } }, { $push: { things: thingObj} }, function(err) { if (err) // handle err ... });
但没有得到任何期望的结果。
在查询中使用$push
操作符将ThingSchema
子文档添加到BoxSchema
的thing
数组中是否正确(如果还有另一个命名相同的子目录,则不能添加subdoc),而不是使用Mongoose Docs ?
编辑:这实际上是问题
我犯了一个错误,上面的代码按预期工作, 但现在我thingObj
的问题是,当thingObj
不匹配的ThingSchema
,一个空的对象插入到things
数组:
// now thingObj is trash var thingObj = { some: "trash", more: "trash" };
在执行给定上述垃圾对象的查询时,以下空对象被插入到子数组中:
{ _id: ObjectId("an_obj_id") }
什么我想这个案件,当thingObj
不匹配的ThingSchema
,是没有什么可添加的。
$addToSet
添加一些独特的数组(如在它检查重复)。 但它只适用于基元。
你应该做的是把things
放入自己的collections品,并在名称上做一个独特的索引。 然后,做这个改变
things: { type: [{type: ObjectId, ref: 'thingscollection'}] }
这样你可以做到
BoxModel.update({ _id: some_box_id, // a valid 'box' ObjectId "things": { "$ne": thingObj._id } }, { $addToSet: { things: thingObj._id} }, function(err) { if (err) // handle err ... });
而当你拿来用, .populate
things
来获得完整的文件。
这不完全是你想要的,但这是一个devise,可以实现你的目标。