Home > Blockchain >  Mongoose: query to get nested multiple related data
Mongoose: query to get nested multiple related data

Time:11-27

I'm new to NoSQL, in this case is MongoDB. I'm trying to make an API using ExpressJS and Mongoose. that have some data models

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

Now I want to perform a query that gets all comments based on specific postId. And the response data must include User data and image url that related to User. I tried this to get comment data

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

It returned Comment with User data, but not include Image. How do I perform that query?

CodePudding user response:

Try this (using the pupulate method with object configuration):

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

Here you can also select particular fields of each schema for example.

Let me know if it works for you.

Reference

  • Related