简体   繁体   English

如何使用 MongoDB 在嵌套数组模式中查询 userId?

[英]How can I query for userId's in a nested Array schema with MongoDB?

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.我无法通过此查询找到这两个用户之间已经存在的对话,并尝试使用 $all 运算符。

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.我之前可以通过省略“参与者”字段来查询对话,因此认为它也适用于该查询,但事实并非如此。

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

It seems like you might be looking for this syntax:看起来您可能正在寻找这种语法:

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

Here's a more detailed info from MongoDB docs .这是来自MongoDB 文档的更详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM