【问题标题】:How can I query for userId's in a nested Array schema with MongoDB?如何使用 MongoDB 在嵌套数组模式中查询 userId?
【发布时间】:2021-12-28 22:29:32
【问题描述】:

我正在尝试查询两个用户之间的现有对话,这样如果他们已经有一个对话,他们就不会在数据库中创建多个对话。

我无法通过此查询找到这两个用户之间已经存在的对话,并尝试使用 $all 运算符。

我之前可以通过省略“参与者”字段来查询对话,所以我认为它也适用于该查询,但事实并非如此。

我需要找到与 BOTH senderId 和 recID 的对话

我做错了什么?

谢谢!

QUERIES 我试过(不工作)

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

型号

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

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

    您似乎正在寻找这种语法:

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

    这是来自MongoDB docs 的更详细信息。

    【讨论】:

    • 我实际上需要确保对话同时具有 senderId 和 recId。有没有办法确保查询只返回具有这两个属性的对象?
    • 那么你需要使用 $and 运算符,我已经编辑了我的答案
    猜你喜欢
    • 2021-01-31
    • 2021-06-29
    • 2012-05-04
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 2021-04-14
    • 2013-06-22
    • 1970-01-01
    相关资源
    最近更新 更多