Answer the question
In order to leave comments, you need to log in
How to write mongoose schema with nested objects?
Hello everyone, I have a post scheme, inside it there is an array with posts, inside the post there is an array with likes
const {
Schema,
model,
ObjectId,
} = require('mongoose');
const likeSchema = new Schema({
id: {type: ObjectId},
userId: {type: ObjectId},
userName: {type: String},
userLastName: {type: String},
})
const postElementSchema = new Schema({
id: {type: ObjectId},
date: {type: String},
time: {type: String},
content: {type: String},
likes: [likeSchema]
})
const PostSchema = new Schema({
id: {type: ObjectId},
userName: {type: String},
userLastName: {type: String},
userAvatar: {type: String},
posts: [postElementSchema]
});
module.exports = model('Post', PostSchema);
const PostSchema = new Schema({
id: {type: ObjectId},
userName: {type: String},
userLastName: {type: String},
userAvatar: {type: String},
posts: {type: Array}
});
const likeParams = (args) => {
return {
id: uuidv4(),
userId: args.userId,
userName: args.userName,
userLastName: args.userLastName,
}
}
const postsData = await MongoosePost.findOne({id: args.ownersId})
postsData.posts.filter(async (post)=> {
if(post.id === args.postId){
post.likes.unshift(likeParams(args))
await post.save()
return post
}
})
Answer the question
In order to leave comments, you need to log in
In such a case, you'd be better off not storing nested objects, but using references and $lookup
(populate in mongoose).
Also read about virtuals
, localField
and foreignField
.
And yes, what is the point of separating Post and Posts?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question