【问题标题】:mongoose model update query猫鼬模型更新查询
【发布时间】:2015-10-21 23:48:02
【问题描述】:

我有这个猫鼬模式

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 运算符时

 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}});

不起作用。

【问题讨论】:

    标签: mongodb mongoose mean-stack


    【解决方案1】:

    看起来您正在调用Array.protoype.pull 的方法,而不是来自猫鼬的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
    });
    
    ....
    

    【讨论】:

      猜你喜欢
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      相关资源
      最近更新 更多