使用$ addToSet

时间:2017-08-31 13:44:11

标签: arrays mongodb mongoose-schema

美好的一天,

我正在尝试保存图片库,其中每个图片最多可以包含5个与之关联的标签。所以在Document中,Gallery字段是一个数组,它有多个值,Tag属性本身就是一个Tags数组。

我在保存图片时遇到问题,用户为该图片添加了2个或更多标签。下面是我的mongoose用户架构

    gallery : [{
        origin : {type: String, trim: true, default: null},
        uploadOn: {type: Date, Default: null},
        title: { type: String, trim: true, default: null},
        caption: { type: String, trim: true, default: null },
        tag: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Imagetag', unique: true, sparse: true }],
        imageLink: { type: String, trim: true }
    }]

这是我的更新脚本<​​/ p>

var query = {username:'testUser'};
var options = { runValidators: true };
var toUpdate = {
      $addToSet : {
        gallery : {
         origin : req.body.orgin,
         uploadOn: new Date(),
         title: req.body.title,
         caption: req.body.caption,

         tag: '59a5fea0382f1305841f0d86' // working
         $addToSet: { tag: { $each: ['59a5fea0382f1305841f0d86', '59a5fea0382f1305841f0d88'] } } , // not working
         $push: { tag: { $each: ['59a5fea0382f1305841f0d86', '59a5fea0382f1305841f0d88'] } } , // not working

         imageLink: req.body.path
       }
     }
};

// proceed to update
var user = await User.findOneAndUpdate(query, toUpdate, options);

我列出了我尝试过的不同组合但没有成功。我不想进行多次调用,以便为同一张图片逐个更新标签。

0 个答案:

没有答案
相关问题