Home > Software engineering >  How to update a specific key of a specific record in MongoDb
How to update a specific key of a specific record in MongoDb

Time:10-15

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.

Please help.

CodePudding user response:

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

  • Related