2017-07-01 160 views
0

我試圖更新角色文件不添加項目,將用戶ID到一個數組_users貓鼬findByIdAndUpdate在陣列

/** 
* 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":[]} 
+0

指定爲數組:''{$ addToSet:{_users:[user._id]}''' – ifiok

+0

謝謝..但它不會改變結果:「_users」:[]。仍然是空的 – erwin

+0

是的,也試過了......沒辦法 roles.findAndModify({_id:ObjectId(「59578d0b01d26507af3fca6c」)},[],{'$ addToSet':{_users:ObjectId(「59578d0c01d26507af3fca73」)}} ,{new:false,upsert:false,fields:{}}) 導致_users:[] – erwin

回答

0

寫不好......

在貓鼬4.0,findByIdAndUpdate(和findOneAndUpdate)的新選項的默認值已更改爲假(請參見發行說明的#2262)。這意味着你需要明確地將選項設置爲true來獲取文檔的新版本,在應用此更新後:

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

所以我寧願寫:

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