Mongoose Populate - Return specific data

Asked

Viewed 21 times

0

I am using populate to return data from the user who created a post. It works well, the problem is that populate returns the entire user, including password hash and other information, but I only need the name and image, so I create a new object only with these two information, I put in the post and give as API response the new formatted data.

I know you have a more direct way of doing this, but I don’t remember, which is to use the populate or other method to return only the specific data of my reference. Which keys do I use?

Model/Schema of the posting:

const modelSchema = new mongoose.Schema({
    author: { type: mongoose.ObjectId, ref: 'users', required: true },
    title: { type: String, required: true, min: 3, max: 100 },
    body: { type: String, required: true },
    creationDate: { type: Date, required: true },
    slug: { type: String, required: true, min: 3, max: 150 },
})

Searching the post together with the data of its creator:

const post = await posts.findOne({ slug: req.params.slug }).populate('author')

The way out looks like:

post: {
    title: 'novo post',
    body: 'apenas um teste',
    creationDate: '2021-05-31',
    slug: 'novo-post',
    author: {
        name: 'teste',
        email: '[email protected]',
        image: 'asdf',
        hash: 'aaaaaaaaaaaaaaaaaaaaaaaaa',
        ...
    }

Then I only get the information I need, but I would like to receive directly from Mongoose the specific Author data.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.