So I have this user model which refers to blog
User Model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bcrypt = require("bcryptjs");
const userSchema = new Schema(
{
email: {
type: String,
required: true,
index: {
unique: true
}
},
password: {
type: String,
required: true
},
name: {
type: String,
required: true
},
website: {
type: String
},
bio: {
type: String
},
blogs: [
{
type: Schema.Types.ObjectId,
ref: "Blog"
}
]
},
{
timestamps: {
createdAt: "created_at",
updatedAt: "updated_at"
}
}
);
userSchema.pre("save", function(next) {
const user = this;
if (!user.isModified("password")) return next();
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function(password, next) {
bcrypt.compare(password, this.password, function(err, isMatch) {
if (err) return next(err);
next(null, isMatch);
});
};
const User = mongoose.model("User", userSchema);
module.exports = User;
And this is my blogs collections which has a reference to comments model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const blogSchema = new Schema(
{
title: {
type: String,
required: true
},
body: {
type: String,
required: true
},
author: {
type: Schema.Types.ObjectId,
ref: "User"
},
likesCount: {
type: Number
},
comments: [
{
type: Schema.Types.ObjectId,
ref: "Comment"
}
]
},
{
timestamps: {
createdAt: "created_at",
updatedAt: "updated_at"
}
}
);
const Blog = mongoose.model("Blog", blogSchema);
module.exports = Blog;
and this is my comments model which has a reference to user model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const CommentSchema = new Schema(
{
body: {
type: String,
required: true
},
likesCount: {
type: Number
},
user: {
type: Schema.Types.ObjectId,
ref: "User"
}
},
{
timestamps: {
createdAt: "created_at",
updatedAt: "updated_at"
}
}
);
const Comment = mongoose.model("Comment", CommentSchema);
module.exports = Comment;
what i want is if i fetch user data i want to fetch blog as well as comment data with in i have this code
exports.getCurrentUser = async (req, res) => {
const ObjectId = mongoose.Types.ObjectId;
const users = await User.findById({ _id: new ObjectId(req.user._id) })
.populate({
path: "blogs",
model: "Blog"
})
.exec();
console.log(users);
return res.status(200).json(users);
};
But its not populating blogs
how can i achieve this kind of nesting reference fetching?