0

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 }
)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I actually need to make sure the Conversation has both senderId & recId. Is there a way to ensure the query only returns an object with both properties?
Then you need to use $and operator instead, I’ve edited my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.