this is my PostSchema creation in mongoose, I've made a reference to the users table in both my post as well as the comment.
const PostSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
text: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
},
comment: [
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
},
text: {
type: String,
require: true,
},
date: {
type: Date,
default: Date.now,
},
},
],
});
What I was trying to do was have the post update the user element on ref, when I am calling it, to provide the user id and the name.
const posts = await Post.find().populate('user', 'name');
Which worked with this, but it didn't do the same for each of the users ref in the comment. Did I do something wrong?
Edit:
const newComment = {
user: user._id,
text: req.body.text,
};
post.comment.unshift(newComment);
await post.save();
This is the code for the comment addition, user._id is the objectId of the current loggedin user.
I even tried making
user: user._id,
to
user: req.user.id,
const newPost = new Post({
text: req.body.text,
title: req.body.title,
user: req.user.id,
});
await newPost.save();
This is the code for the newPost, again req.user.id is the ID of the current loggedin in.
Edit:
this is user schema
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('users', userSchema);