Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoError: cannot infer query fields to set, path 'users' is matched twice

I am using mongoose. I want to create a document chat with an array users (including userId1, userId2), if I do not find it:

This is how I do:

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

But I got the error:

MongoError: cannot infer query fields to set, path 'users' is matched twice

This is Chat Schema:

{
  users: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  createdAt: { type: Date, default: Date.now }
}

How can I do it correctly? Thanks

like image 438
Hongbo Miao Avatar asked Aug 21 '16 04:08

Hongbo Miao


2 Answers

I use this as the condition

{
  "users": {
        $all: [
          {"$elemMatch": userId1},
          {"$elemMatch": userId2}
        ]
  }......
}
like image 145
opcode Avatar answered Nov 19 '22 20:11

opcode


I know this already has an answer but to hopefully save someone else some time, I had to do this:

{
  "users": {
        $all: [
          { $elemMatch: { $eq: mongoose.Types.ObjectId(userId1) }},
          { $elemMatch: { $eq: mongoose.Types.ObjectId(userId2) }}
        ]
  }......
}

Modifications from accepted answer:

  • The $eq was needed just like Dave Howson said in his comment on the accepted answer.
  • mongoose.Types.ObjectId was needed because I guess the _id property on my schema instance was a string.
like image 44
Reece Kenney Avatar answered Nov 19 '22 20:11

Reece Kenney