首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模式模式查询

模式模式查询
EN

Stack Overflow用户
提问于 2022-06-03 11:35:01
回答 1查看 22关注 0票数 0

这里有两个模式,用户模式和连接模式。用户架构具有电子邮件、名称和密码。连接模式是指UserID等于用户的_id,hasRequested --该数组由请求连接&isConnectionE29的用户的_id组成--一个数组具有用户的_idE 110连接到用户E 211。假设有一个具有_id A的用户,并且有两个连接(与_id B和C)。假设B有连接A,X,Y,假设C有连接A,M,N。我应该写什么MongoDB查询,这样我就可以得到A的连接,以及B和C的连接,或者简单地说连接。

模式->>

代码语言:javascript
复制
const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
    },
    password: {
        type: String,
        required: true
    }
}, { timestamps: true });
代码语言:javascript
复制
const ConnectionSchema = new mongoose.Schema({
    UserID: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
        required: true
    },
    hasRequested: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }],
    isConnection: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }]
})
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-03 13:18:45

不幸的是,无法在这些文档之间嵌套填充。为了达到这个目标,你应该提出分开的请求。但是,如果您将它们组合在一起,如:

代码语言:javascript
复制
const UserSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
    hasRequested: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
    ],
    isConnection: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }]
  },
  { timestamps: true }
);

然后,您可以使用这个查询来获取您想要的请求:

代码语言:javascript
复制
await User.findOne({ _id: userID }).populate(path = "hasRequested", populate = "hasRequested");
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72489009

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档