蓝鸟承诺:为什么返回值不如预期?

时间:2017-05-31 08:47:15

标签: mongoose promise bluebird

我正在更新具有多个Role子文档的Group文档,但返回的值不是更新后的组:

该组正确更新:

Mongoose: groups.update({ _id: ObjectId("592e823e61229c36f3436e06") }, { '$push': { roles: { 
'$each': [ { _id: ObjectId("592e823f61229c36f3436e0c"), description: 'Description Role0', name:
'Role0' }, { _id: ObjectId("592e823f61229c36f3436e0b"), description: 'Description Role1', name:
'Role1' }, { _id: ObjectId("592e823f61229c36f3436e0a"), description: 'Description Role2', name:
'Role2' }, { _id: ObjectId("592e823f61229c36f3436e09"), description: 'Description Role3', name:
'Role3' } ] } }, '$setOnInsert': { __v: 0 } }, { upsert: true })

在控制台中显示更新的组,Iget:

  UPDATED GROUP WITH ROLES: {"n":1,"nModified":1,"ok":1}

使用此代码:

  addMultipleRoles(groupId, n) {
    const multiRoles = [];
    for (let i = 0; i < n; i += 1) {
      multiRoles.push({ groupId: groupId, name: `Role${i}`, description: `Description Role${i}` });
    }
    return Group.update({_id: groupId}, {$push: {roles: {$each: multiRoles}}}, {upsert:true} )
      .then((savedGroup) => {
        console.log('UPDATED GROUP WITH ROLES: %j', savedGroup);
        return savedGroup;
      })
      .catch((e) => {
        if (e.name === 'ValidationError' && e.errors.name.kind === 'unique') {
          console.log( 'Existing role(s)');
        } else {
          console.log('error saving multi roles %j', e);
        }
        return [];
      });
  },

1 个答案:

答案 0 :(得分:0)

这就是MongoDB的update所做的:它更新数据库中的文档并返回所谓的WriteResult

如果您想要检索更新的文档,可以将findOneAndUpdatenew选项结合使用:

Group.findOneAndUpdate({
  _id : groupId
}, {
  $push : { roles : { $each : multiRoles } }
}, {
  upsert : true,
  new    : true
}).then(...)