【问题标题】:Mongoose Update array in a document does not work as expected文档中的 Mongoose 更新数组无法按预期工作
【发布时间】:2018-10-05 23:52:49
【问题描述】:

几天前我一直在摸索如何使用 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
}

谁能指导我同时更新创作者分数和所有合作伙伴分数?

【问题讨论】:

    标签: database mongodb mongoose


    【解决方案1】:

    我对模型上的 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 })
              })});
            })
    

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2021-04-08
      • 2015-11-25
      • 2021-02-01
      • 2014-11-03
      • 1970-01-01
      相关资源
      最近更新 更多