R
R
Raybul2022-02-23 20:48:54
MongoDB
Raybul, 2022-02-23 20:48:54

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);

the structure should be something like this, but it doesn't work (
if I do this
const PostSchema = new Schema({
    id: {type: ObjectId},
    userName: {type: String},
    userLastName: {type: String},
    userAvatar: {type: String},
    posts: {type: Array}
});

then everything is fine, but I need to describe nested arrays so that I can edit nested objects like this
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
            }
        })

does not work without typing nested objects

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rag'n' Code Man, 2022-02-23
@iDmitriyWinX

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, localFieldand foreignField.
And yes, what is the point of separating Post and Posts?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question