0

My goal is to add a comment to my CommentFeed and while doing that I want to push that comment into my topComments field and also update the 'numOfComments' . I want to limit the topComments to only 3 comments (How would I even set that up?). And how do I take the previous value of numOfComments and add one to it?

 CommentFeed.findOneAndUpdate(
            { _id: commentId },
            {
                $push: {
                    comments: {
                        text: req.body.text
                    },
                 $push: topComments:{text: req.body.text}, <--- Limit this somehow to only allow an array length of 3?
                 $set: numOfComments: ? ,  <---What kind of logic is used here?
                }
            },
            { new: true }
        )

CommentFeed Schema

    const CommentFeedSchema = new Schema({
              topComments:[{text:{type:String}}],
              numOfComments:{type:Number},
              comments: [
                   text: { type: String, required: true }
                    ]});
Snoopy
  • 1,257
  • 2
  • 19
  • 32
  • Possible duplicate of [How to limit an array size in MongoDB?](https://stackoverflow.com/questions/29932723/how-to-limit-an-array-size-in-mongodb) – OzW Mar 27 '19 at 11:10

1 Answers1

0

For the first issue (limiting the topComments array size) you can use the $slice operator. This has already been answered in other questions. But you might consider computing topComments from comments using the$slice operator in the projection argument:

CommentFeed.find( {}, { comments: { $slice: -3 } } )

For the second issue (updating a document using existing fields from that document), it is not something you can do in a simple findOneAndUpdate call. This was also discussed in other questions. But you might consider computing numOfComments instead of updating it every time. You can do that with the $size operator of the aggregation framework:

CommentFeed.aggregate({$project: { numOfComments: { $size:"$comments" }}})
OzW
  • 848
  • 1
  • 11
  • 24