MongoError:无法推断要设置的查询字段,路径“用户”被匹配两次

Hon*_*iao 7 upsert mongoose mongodb mongodb-query

我在用猫鼬。如果找不到,我想创建一个chat带有数组users(包括userId1userId2)的文档:

这是我的方法:

ChatModel.findOneAndUpdate(
  { users: { $all: [userId1, userId2] }},
  { $setOnInsert: {
    users: [userId1, userId2]
  }},
  { upsert: true })
  .exec()
  .catch(err => console.log(err));
Run Code Online (Sandbox Code Playgroud)

但是我得到了错误:

MongoError:无法推断要设置的查询字段,路径“用户”被匹配两次

这是Chat模式:

{
  users: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  createdAt: { type: Date, default: Date.now }
}
Run Code Online (Sandbox Code Playgroud)

如何正确执行?谢谢

小智 5

我用这个作为条件

{
  "users": {
        $all: [
          {"$elemMatch": userId1},
          {"$elemMatch": userId2}
        ]
  }......
}
Run Code Online (Sandbox Code Playgroud)

  • 这会导致 _$elemMatch 需要一个 Object_ 错误。可以通过使用`$eq`运算符来解决,比如`{$elemMatch: {$eq: userId1}},` (3认同)