我有这个猫鼬模式
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var imageModel = new Schema({
url: {type: String}
});
var albumModel = new Schema({
name: {type:String},
images: [imageModel]
});
module.exports = mongoose.model("Album",albumModel);
此架构的一个实例是
{
_id: 55ba2588e8e0f5d80f752889,
name: 'album1',
__v: 0,
images:
[ {
url: 'images_uploaded/photo1.gif',
_id: 55ba2588e8e0f5d80f75288e
},
{
url: images_uploaded/photo2.jpg',
_id: 55ba2588e8e0f5d80f75288d
}]
}
我会从相册中删除来自用户请求的其他json对象中不存在的图像
console.log(req.body)
{
_id: 55ba2588e8e0f5d80f752889,
name: 'album1',
images:
[{
url: images_uploaded/photo2.jpg',
_id: 55ba2588e8e0f5d80f75288d
}]
}
应从子文档中删除photo1.gif
我试过
album.images.pull({"_id":"55ba2588e8e0f5d80f75288e "});
这个工作正常,但是当我使用$ nin operator
时 var ids = [];
for(var i=0; i< req.body.images.length; i++)
{
ids.push(req.body.images[i]._id);
}
req.album.images.pull({"_id":{$nin: ids}});
不起作用。
答案 0 :(得分:0)
您似乎在Array.protoype.pull
调用该方法,而不是来自mongoose的pull
。但是这里是如何从数组中嵌套对象中提取的。
var Album = require("albumModel");
....
var ids = req.body.images.map(function(image){ return image._id });
Album.update({}, { $pull: { images: { $elemMatch: { _id: { $nin: ids } } } } }).exec(function(err) {
// Do something
});
....