简体   繁体   中英

Incrementing JSON field using PUT and update() mongoose

I'm trying to simply add 1 to a variable I have stored in a JSON file.

This is what I'm using to accomplish this:

app.put('/api/listing/:street/:buildingNumber/:apartmentNumber/incrementFlagCount', function (req, res) {
        console.log("incrementing flag count now");

        mongoose.model('Listing').findOne(req.street, req.buildingNumber, req.apartmentNumber, function(err, listing){
            listing.update({
             //   $inc : {flagCount : 1}
                flagCount : flagCount+1
            },function(err){
                if(err){
                    res.send("There was a problem incrementing the flagCount of a listing: " + err);
                }
                else{
                    console.log("Flag count after=" + listing.flagCount);
                    res.json(listing.flagCount);
                }
            })
        });
    });

I'm getting the following error: ReferenceError: flagCount is not defined This is how the JSON looks in mongolab:

{
    "_id": {
        "$oid": "566c4bbabcda51a9eef08578"
    },
    "street": "test",
    "buildingNumber": 1,
    "apartmentNumber": 1,
    "beds": 1,
    "price": 1,
    "flagCount": 3,
    "owner": "56472a83bd9fa764158d0cb6"
}

What am I doing wrong? I just want to increment the flagCount by 1.

Your calls to findOne and update with flagCount are incorrect. findOne needs an object of conditions.

You also should use req.params.street instead of req.street , etc.

Rather than a find and then update, how about using findOneAndUpdate?

mongoose.model('Listing').findOneAndUpdate({street: req.params.street, 
buildingNumber: req.params.buildingNumber,
apartmentNumber: req.params.apartmentNumber}, {$inc: {flagCount: 1}}, 
    function(err, listing) {
     /// do stuff 
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM