在单个查询中更新文档并上载子文档

时间:2019-08-16 11:28:43

标签: mongodb mongoose

如何在单个查询中更新父文档中的项目并增补子文档?

这是我的示例架构。

const ExampleSchema = new Schema({
  user_count: {
    type: String,
    default: 0
  },
  users: [
    {
      id: {
        type: Schema.Types.ObjectId,
        ref: "users",
        unique: true
      },
      action: {
        type: Boolean
      }
    }
  ],

});

我想在单个查询中将+1添加到user_count并将文档向上插入到用户数组。

const result = await Example.updateOne(
      {
        _id: id,
      },
      {
        $set: {
          "user_count": user_count++,
          "users.$.id": req.user.id,
          "users.$.action": true
        } 
      },
      { upsert: true }
    );

我已经尝试了上面的代码,但是遇到了以下错误。

[0]    'The positional operator did not find the match needed from the query.',
[0]   [Symbol(mongoErrorContextSymbol)]: {} }

2 个答案:

答案 0 :(得分:1)

我对猫鼬不熟悉,所以我认为"user_count": user_count++可以正常工作。

对于其他情况,有两件事是行不通的:

  • $中的"users.$.id": req.user.id,运算符被称为位置运算符,这不是您想要的,它用于更新数组中的特定元素。在这里进一步阅读:https://docs.mongodb.com/manual/reference/operator/update/positional/

  • 如果upsert与集合中的任何内容都不匹配,则update将插入完整的文档。在您的情况下,您只想向右推数组中的元素?

在这种情况下,我猜可能是这样的:

const result = await Example.updateOne(
      {
        _id: id,
      },
      {
        $set: {
          "user_count": user_count++
        },
        $addToSet: {
           "users": {
              "id": req.user.id,
              "action": true
           }
        }
      }
    );

请注意,$push可能也会代替$addToSet来解决问题。但是$addToSet会在您的数组中保持唯一性。

答案 1 :(得分:0)

db.collection.findOneAndUpdate({_id: id}, {$set: {"user_count": user_count++},$addToSet: {"users": {"id": req.user.id,"action": true}}}, {returnOriginal:false}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});
相关问题