Bluebird Promise:为什么返回值不符合预期?

Bluebird Promise : why returned value is not as expected?

我正在更新一个包含多个 Role 子文档的组文档,但返回的值不是更新后的组:

群组更新正确:

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 })

在控制台中显示更新的组,我得到:

  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 [];
      });
  },

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

如果要检索更新的文档,可以使用 findOneAndUpdate 结合 new 选项:

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