Im having 2 different models in my code :
- User Schema
let userSchema = new Schema({
_id: Schema.Types.ObjectId,
name: { type: String, default: '', required: true },
comments: [{
type: Schema.Types.ObjectId, ref: 'Comment'
}]
});
const User = model('User', userSchema,'User');
- Comment Schema
const commentSchema = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'User'},
text: { type: String, default: '', required: true },
});
const Comment = model('Comment', commentSchema, 'Comment');
so when I make a new user, it has an empty comments array which is ok
Example user :
{
"_id": "62da583a27c7bf8a5b3ce118",
"name": "saleh gholami",
"comments": []
}
but when I make a new comment, it'll only set the author of the comment object
Example comment :
{
"author": "62da583a27c7bf8a5b3ce118",
"text": "Hello World !",
"_id": "62da583d27c7bf8a5b3ce11b"
}
What I'm expecting to see is that when I save a new comment object, It'd add the id of the comment to a field of user's object which is an array and it's called comments
Example of what I expect :
{
"_id": "62da583a27c7bf8a5b3ce118",
"name": "saleh gholami",
"comments": ["62da583a27c7bf8a5b3ce118"] //array of user's comments ids
}
But I'm still getting the empty array
1. Should I push the new comment ids manually each time ?
2. Or is there any way to automatically sync the array field with the new values?