0

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?

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your kindness. I had one but was resolved by myself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.