1
I imagine it’s something very simple to solve but I’m already several hours trying to solve and I get nowhere.
I’m developing a blog as a way of study but I’m having problems using the populate()
of Mongoosis.
I have the following models:
Posts.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const PostSchema = new Schema({
title:
{
type: String,
required: true,
},
category:
{
type: Schema.Types.ObjectId,
ref: 'categories',
required: true
},
text:
{
type: String,
required: true
}
})
module.exports = mongoose.model('posts', PostSchema)
Categories.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const CategorySchema = new Schema({
title:
{
type: String,
required: true
}
})
module.exports = mongoose.model('categories', CategorySchema)
And the code to show all posts made, including the title of the category:
Indexcontroller.js
const Post = require('../models/Posts');
exports.Index = (req, res) =>
{
Post.find({}).
populate('categories').
exec((err, post) =>
{
res.json(post);
})
}
The problem is the only return I get is from id
of the category:
[{"_id":"60198923d4323f3630468fce",
"title":"Titulo qualquer",
"category":"60198651822d5147c041eaee",
"text":"Texto qualquer","__v":0}]
Someone could give me a light?