mongoose findByIdAndUpdate不在数组

时间:2017-07-01 11:01:46

标签: node.js mongoose

我正在尝试更新Role文档,将userId添加到数组_users

/**
 * Role Schema
 */
const RoleSchema = new Schema({
  _group: { type: ObjectId, ref: 'Group'},
  _users: [{ type: ObjectId, ref: 'User' }],
  name: { type: String, required: true },
  description: { type: String, trim: true, },
});

运行以下

  console.log('GOING TO ADD user._id: ', user._id, 'INTO ROLE: ', req.body.roleId);
  Role.findByIdAndUpdate(new ObjectId(req.body.roleId), 
 { $addToSet: { _users: user._id }, upsert: true })
    .exec()
    .then((updatedRole) => {
      console.log('updated role: %j', updatedRole);
      res.json(updatedRole);
    })
    .catch((e) => {
      console.log('ERROR SAVING ROLE: %j', e);
      throw(e);
    });

_users数组没有更新......为什么?

    GOING TO ADD user._id:  59577f9b660489066515ce9c INTO ROLE:  59577f99660489066515ce95

    Mongoose: roles.findAndModify({ _id: ObjectId("59577f99660489066515ce95") }, [], { '$addToSet': 
 { _users: ObjectId("59577f9b660489066515ce9c") } }, 
 { new: false, upsert: false, fields: {} })

    updated role: {"_id":"59577f99660489066515ce95","__v":0,
 "_group":"59577f99660489066515ce92","name":"admin",
 "description":"can RW group, user","rolePermissions":[],
 "permissions":[{"resourceName":"group",
  "authorizedActions":["read","write"]}
  {"resourceName":"user","authorizedActions":["read","write"]}],
  "_users":[]}

1 个答案:

答案 0 :(得分:0)

糟糕的写作......

在Mongoose 4.0中,新选项findByIdAndUpdate(和findOneAndUpdate)的默认值已更改为false(请参阅发行说明的#2262)。这意味着在应用更新后,您需要将选项显式设置为true以获取新版本的文档:

Model.findByIdAndUpdate(id, updateObj, {new: true}, function(err, model) {...

所以我宁愿写:

Role.findByIdAndUpdate(req.body.roleId, { $addToSet: { _users: new ObjectId(user._id) }} , { new: true })