文档中的猫鼬更新数组无法按预期工作

时间:2018-10-04 16:06:28

标签: database mongodb mongoose

几天以来,我一直在摸索如何使用Mongoose更新数组的内容。

以下是我的模式:

const playedGameSchema = new Schema ({
  created: Date,
  updated: Date,
  game: {
    type: Schema.Types.ObjectId,
    ref: 'game'
  },
  creator: {
    id: {
      type: Schema.Types.ObjectId,
      ref: 'user'
    },
    score: Number
  },
  partners: [{
    id: {
      type: Schema.Types.ObjectId,
      ref: 'user'
    },
    score: Number
  }]
});

module.exports = mongoose.model('PlayedGame',playedGameSchema);

基本上,我想同时实现:  -更新creator.score(成功使用圆点表示法)。  -更新每个合作伙伴的得分键(不成功)。

这是文档创建的结果:

{
    "creator": {
        "id": "5b8544fa11235d9f02a9b4f1",
        "score": 0
    },
    "_id": "5bb6375f5f68cc5c52bc93ae",
    "game": "5b45080bb1806be939bfde03",
    "partners": [
        {
            "_id": "5bb637605f68cc5cafbc93b0",
            "id": "5b85497111235d677ba9b4f2",
            "score": 0
        },
        {
            "_id": "5bb637605f68ccc70ebc93af",
            "id": "5b85497111235d677ba9b4f2",
            "score": 0
        }
    ],
    "created": "2018-10-04T15:53:03.386Z",
    "updated": "2018-10-04T15:53:03.386Z",
    "__v": 0
}

正如我所说,我可以通过传递类似{ "creator.score": 500 }之类的东西作为第二个参数来更改得分创建者的得分,然后切换到尝试更新数组。

这是我的lambda函数,用于更新每个合作伙伴的得分:

export const update: Handler = (event: APIGatewayEvent, context: Context, cb: Callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  const body = JSON.parse(event.body);
  let partnersScore: object = {};

  if(body.update.partners) {
    body.update.partners.forEach((score, index) => {
      const key = `partners.${index}.$.score`;
      partnersScore = Object.assign(partnersScore, { [key]: score});
      console.log(partnersScore);
    });
  }

  connectToDatabase().then(() => {
    console.log('connected', partnersScore)
    PlayedGame.findByIdAndUpdate(body.id, { $set: { partners: partnersScore } },{ new: true})
      .then(game => cb(null, {
        statusCode: 200,
        headers: defaultResponseHeader,
        body: JSON.stringify(game)
      }))
      .catch(err => {
        cb(null, {
        statusCode: err.statusCode || 500,
        headers: { 'Content-Type': 'text/plain' },
        body: err
      })});
  });
}

{ 'partners.0.$.score': 500, 'partners.1.$.score': 1000 }传递给$set

不幸的是,我请求的结果是一个伙伴数组,其中仅包含一个空对象。

{
    "creator": {
        "id": "5b8544fa11235d9f02a9b4f1",
        "score": 0
    },
    "_id": "5bb6375f5f68cc5c52bc93ae",
    "game": "5b45080bb1806be939bfde03",
    "partners": [
        {
            "_id": "5bb63775f6d99b7b76443741"
        }
    ],
    "created": "2018-10-04T15:53:03.386Z",
    "updated": "2018-10-04T15:53:03.386Z",
    "__v": 0
}

有人能指导我更新创作者分数和所有合作伙伴的分数吗?

1 个答案:

答案 0 :(得分:0)

我对模型上的findOneAndUpdate方法的看法是,这样做比较好,因为它不需要在BDD之外更改数据,但是想要更新数组键和另一个键似乎很困难。

相反,我依赖于设置/保存逻辑,如下所示:

PlayedGame.findById(body.id)
      .then(game => {
        game.set('creator.score',  update.creatorScore);
        update.partners.forEach((score, index) => game.set(`partners.${index}.score`, score));

        game.save()
          .then(result => {
            cb(null, {
              statusCode: 200,
              headers: defaultResponseHeader,
              body: JSON.stringify(result)
            })
          })
          .catch(err => {
            cb(null, {
            statusCode: err.statusCode || 500,
            headers: { 'Content-Type': 'text/plain' },
            body: JSON.stringify({ 'Update failed: ': err })
          })});
        })