How to update a specific key of a specific record in MongoDB

Issue

I’m storing some Article in MongoDB. By Article I mean this structure:

const articleSchema = new Schema({
    articleid: String,
    title: String,
    content: String,
    date: String,
    contributor: String,
    upvotes: Number,
    upvoters: [String], //<--------- I NEED HELP WITH THIS
    downvotes: Number,
    downvoters: [String]
})

I’m creating an API in NodeJS. Using this end point I want to add current upvoting user to be added in upvoters array in MongoDB:

router.post('/upvoted/:articleid/:userid', (req, res) => {
    Article.findOneAndUpdate({ articleid: req.params.articleid }, { upvoters: ["req.params.userid"] }, (failure, success) => {
        if (success) {
            res.status(200).send("done")
        }
        else {
            res.status(200).send("not done")
        }
    })
})

My problem is that the array is getting replaced entirely. I want to append this user into the same upvoters array in MongoDB.

Solution

Use $push operator to add an element to the array.

Article.findOneAndUpdate({ articleid: req.params.articleid }, { $push: { upvoters: req.params.userid }}, (failure, success) =>...

You can read more here

Answered By – qve1t

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published