简体   繁体   English

使用猫鼬更新数组

[英]Using mongoose to update an array

I have an array field in mongoose which I need to update. 我在猫鼬中有一个数组字段,需要更新。 Right now I am using the foloowing: 现在,我正在使用以下方法:

 var fieldsToSet = {
      somename: req.body.username,
      email: req.body.email.toLowerCase(),
      $addToSet:{array_field:'some single value'},
      search: [
        req.body.username,
        req.body.email,

      ],
    };

I update it using 我使用更新

 req.app.db.models.User.findByIdAndUpdate(req.user.id, fieldsToSet, options, function(err, user) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.emit('patchAdmin', user);
    });

However it does not seem to work. 但是,它似乎不起作用。 COuld someone please help me out? 有人可以帮我吗?

var userSchema = new mongoose.Schema({
    username: { type: String, unique: true },
    password: String,
     array_field:[String],
    email: { type: String, unique: true },

You cannot mix what are essentially two types of "update" options. 您不能混合使用本质上两种类型的“更新”选项。 MongoDB will either "replace" the whole document with the arguments provided or apply the "operators" you specify. MongoDB将使用提供的参数“替换”整个文档,或应用您指定的“运算符”。

It appears that you want $set here as well: 似乎您也希望在此处$set

var fieldsToSet = {
      "$set": {
          "somename": req.body.username,
          "email": req.body.email.toLowerCase(),
          "search": [
            req.body.username,
            req.body.email,
          ]
      },
      "$addToSet":{ "array_field": 'some single value' },
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM