【问题标题】:Mongoose: query to get nested multiple related dataMongoose:查询以获取嵌套的多个相关数据
【发布时间】:2021-11-27 00:16:43
【问题描述】:

我是 NoSQL 的新手,在本例中是 MongoDB。我正在尝试使用ExpressJSMongoose 制作API。有一些数据模型

User.js

const UserSchema = new mongoose.Schema(
    {
        username: {
            type: String,
            required: true,
            min: 3,
            max: 50,
            unique: true,
        },
        email: {
            type: String,
            required: true,
            max: 50,
            unique: true,
        },
        password: {
            type: String,
            required: true,
            min: 6,
        },
        profilePicture: {
            type: Schema.Types.ObjectId,
            ref: "Image",
        },
}

Image.js

const ImageSchema = new mongoose.Schema(
    {
        desc: {
            type: String,
        },
        url: {
            type: String,
        },
    },
    { timestamps: true }
)

Post.js


const PostSchema = new mongoose.Schema(
    {
        username: {
            type: String,
            required: true,
        },
        title: {
            type: String,
            required: true,
        },
        desc: {
            type: String,
            max: 300,
            required: true,
        },
        images: [
            {
                type: Schema.Types.ObjectId,
                ref: "Image",
            },
        ],
        comments: [
            {
                type: Schema.Types.ObjectId,
                ref: "Comment",
            },
        ],
    }
)

Comment.js

const CommentSchema = new mongoose.Schema(
    {
        user: {
            type: Schema.Types.ObjectId,
            ref: "User",
        },
        text: {
            type: String,
            required: true,
            trim: true,
        },
}

现在我想执行一个查询,根据特定的postId 获取所有 cmets。并且响应数据必须包括User数据和image urlUser相关的数据。我试过这个来获取评论数据

const comments = await Comment.find({post: req.params.postId}).populate("user")

它返回 CommentUser 数据,但不包括 Image。如何执行该查询?

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    试试这个(使用 pupulate 方法和对象配置):

    const comments = await Comment.find({post: req.params.postId}).populate({
      path: 'user',
      populate: {
        path: 'profilePicture'
      }
    })
    

    例如,您还可以在此处选择每个架构的特定字段。

    让我知道它是否适合你。

    Reference

    【讨论】:

    • 感谢您的好意。我有一个,但我自己解决了。
    猜你喜欢
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多