【问题标题】:How to get the result of a monogdb populated items如何获取 mongodb 填充项目的结果
【发布时间】:2022-01-25 06:57:41
【问题描述】:

我有一个文件模型引用了一个笔记模型,而该笔记引用了一个问题模型。

一个文件可以有很多注释,不同的注释可以有很多问题,如何在MongoDB中通过文件ID查询文件,返回文件下所有注释下的所有问题。

文件--->注释--->问题

const mongoose = require('mongoose');
const { Schema } = mongoose;

mongoose.Promise = global.Promise;

const fileSchema = new Schema(
    {
        title: {
            type: String,
            required: [true, 'Please add a title'],
            trim: true,
        },
        user: {
            type: mongoose.Schema.ObjectId,
            ref: 'User',
            required: true,
        },
        notes: [
            {
                type: mongoose.Schema.ObjectId,
                ref: 'Note',
            },
        ],
       
    },
    {
        timestamps: true,
        toJSON: { virtuals: true },
        toObject: { virtuals: true },
    },
);

module.exports = mongoose.model('File', fileSchema);


const mongoose = require('mongoose');
const { Schema } = mongoose;

mongoose.Promise = global.Promise;

const noteSchema = new Schema(
    {
        title: {
            type: String,
            required: [true, 'Please add a title'],
            trim: true,
        },
       
        user: {
            type: mongoose.Schema.ObjectId,
            ref: 'User',
            required: true,
        },
       
        questions: [
            {
                type: mongoose.Schema.ObjectId,
                ref: 'Question',
            },
        ],
      
    },
    {
        timestamps: true,
        toJSON: { virtuals: true },
        toObject: { virtuals: true },
    },
);

【问题讨论】:

    标签: javascript node.js mongodb mongoose-schema


    【解决方案1】:

    这看起来类似于 Mongoose 的 Populating across multiple levels 示例

    假设您有一个跟踪用户朋友的用户模式。

    const userSchema = new Schema({
     name: String,
     friends: [{ type: ObjectId, ref: 'User' }]
    });
    

    Populate 可让您获取用户的朋友列表,但如果您还想要用户的朋友的朋友怎么办?指定填充选项告诉猫鼬填充所有用户朋友的朋友数组:

    User.
      findOne({ name: 'Val' }).
      populate({
        path: 'friends',
        // Get friends of friends - populate the 'friends' array for every friend
        populate: { path: 'friends' }
      });
    

    在您的情况下,它可能如下所示:

    File
      .findById(id)
      .populate({
        path: 'notes',
        populate: { path: 'questions' }
      });
    

    【讨论】:

      猜你喜欢
      • 2020-03-23
      • 2021-09-19
      • 1970-01-01
      • 2015-03-02
      • 2013-05-17
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2020-08-19
      相关资源
      最近更新 更多