【问题标题】:MongoDB Mongoose: Get data from two collection in one callMongoDB Mongoose:一次调用从两个集合中获取数据
【发布时间】:2019-11-13 19:31:45
【问题描述】:

所以我有一个用于保存文章的集合,这个集合中的一个键是userId,我在其中保存用户集合中的_id。

const articleSchema: Schema = new Schema(
  {
    body: { type: String },
    title: { type: String, required: true },
    subTitle: { type: String, required: true },
    userId: { type: Number, required: true, index: true },
  },
  {
    timestamps: true,
  }
);

当我得到其中一篇文章时,我还想获取存储在用户集合中的用户名和其他信息。


const userSchema: Schema = new Schema(
  {
    email: { type: String, required: true, unique: true, index: true },
    country: { type: String },
    fullName: { type: String, required: true },
    password: { type: String, required: true },
  },
  {
    timestamps: true,
  }
);

我必须对数据库进行 2 次调用还是有某种方法可以只调用一次?类似于 SQL 中的联接

const account = await articleSchema // <-----can I also select the userSchema?
        .findOne(
          { userId }
        )
        .exec();

如果可能的话,我想在一次调用中获取文章和撰写文章的用户详细信息

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    你可以看看这个Lookup

    对同一数据库中的未分片集合执行左外连接,以过滤来自“已连接”集合的文档以进行处理

    {
     $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
    }
    

    【讨论】:

      【解决方案2】:

      您需要在您的文章架构中添加引用,以便您可以在您的文章架构中将 userId 更改为以下:

      userId: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'userSchema', // put user schema here
          required: true
      }
      

      并像这样编写查询:

      const account = await articleSchema
          .findOne(
            { userId: userId_value_here }
          ).populate('userId', 'email fullName')
      

      它将在 userId 键中为您提供带有 User 对象的 Article 对象 输出如下:

      {
      "_id" : ObjectId("5dca81898cc8cc03a4a759b0"),
      "__v" : 0,
      "body" : "body",
      "title" : "title",
      "subTitle": "sub title",
      "userId": {
                    "_id" : ObjectId("5dca81898cc8cc03d56s6ada"),
                    "email": "email@email.com",
                    "fullName" : "name"
                }
      }
      

      【讨论】:

        【解决方案3】:

        使用查找,它将从用户集合中返回用户的详细信息。

          db.collection('articles').aggregate([{$lookup:{from:"users",localField:"userId",foreignField:"_id", as:"userDetails"}}])
        

        【讨论】:

          猜你喜欢
          • 2012-06-04
          • 1970-01-01
          • 1970-01-01
          • 2018-08-21
          • 2016-06-20
          • 2021-09-27
          • 2021-12-11
          • 2019-01-13
          • 1970-01-01
          相关资源
          最近更新 更多