Home > Net >  How can I query for userId's in a nested Array schema with MongoDB?
How can I query for userId's in a nested Array schema with MongoDB?

Time:12-29

I am trying to query for an existing conversation between two users so they don't create more than one conversation in the database if they already have one.

I am not able to get this query to find a conversation that already exists between these two users and tried to use the $all operator.

I was able to query for a conversation by leaving out the "participants" field before so thought it would also work for this query but it isn't.

I need to find a conversation with BOTH senderId & recID

What am I doing wrong?

Thanks!

QUERIES I tried (Not working)

// 1
 const existingConvo = await Conversation.findOne({
      userId: { $all: [newMsg.senderId, newMsg.recId] },
    })
// 2
const existingConvo = await Conversation.findOne({
      userId: [newMsg.senderId, newMsg.recId],
    })

Model

const conversationSchema = mongoose.Schema(
  {
    participants: [participantSchema],
  }
)

const participantSchema = mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      required: true, // false because we can generate notifications
      ref: `User`,
    },
    username: {
      type: String,
      required: true,
    },
    profileUrl: {
      type: String,
      required: true,
    },
  },
  { _id: false }
)

CodePudding user response:

It seems like you might be looking for this syntax:

{ $and: [ { userId: newMsg.senderId }, { userId: newMsg.recId }] }

Here's a more detailed info from MongoDB docs.

  • Related