【问题标题】:Bluebird Promise : why returned value is not as expected?Bluebird Promise:为什么返回值不符合预期?
【发布时间】:2017-10-31 23:21:06
【问题描述】:

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

组已正确更新:

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

【问题讨论】:

    标签: mongoose promise bluebird


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 2022-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多