Search code examples
mongodbreactjssubdocument

mongoose and subcollection approach


Im starting my own project - portal about football club with simple CMS in react/redux and nodejs. I want allow ppl to answer to another comment. I thought about subcollection in mongoose. I would have main collection called COMMENT. It would have ref to USER collection (f.e If I want to check something about user - author of comment). In COMMENT collection I would want to have sub collection of all answers to this comment - an array. Something like this:

/USER COLLECTION/
{
    _id:52
    username: John
    /.../
}

/COMMENT COLLECTION/
{
    ref: id from user collection (52),
    commentID: 13
    answers: [subComment]
}

/SUB_COMMENT COLLECTION/
{
    ref: commentID (13)
    author: String
    /.../
}

Will it work? Will I be able to query from comment collection to user? Will I have access to user values from comment collection thanks to simple 'ref'?


Solution

  • Yes it will work. As long as you have the relationships defined correctly, you can alway get a user's comments and subcomments using mongoose populate. You can read up about it here