【问题标题】:Incrementing JSON field using PUT and update() mongoose使用 PUT 和 update() mongoose 增加 JSON 字段
【发布时间】:2016-03-19 04:30:12
【问题描述】:

我正在尝试将 1 简单地添加到我存储在 JSON 文件中的变量中。

这就是我用来完成此任务的方法:

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);
                }
            })
        });
    });

我收到以下错误:ReferenceError: flagCount is not defined 这是 JSON 在 mongolab 中的样子:

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

我做错了什么?我只想将flagCount 增加 1。

【问题讨论】:

  • 尝试listing.update.flagCount
  • @Manu got TypeError: listing.update.flagCount is not a function

标签: javascript json node.js mongodb mongoose


【解决方案1】:

您使用 flagCount 对 findOneupdate 的调用不正确。 findOne 需要一个条件对象。

您还应该使用req.params.street 而不是req.street 等。

而不是查找然后更新,使用 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 
})

【讨论】:

    猜你喜欢
    • 2012-12-14
    • 2020-08-15
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2017-01-30
    • 2017-03-15
    相关资源
    最近更新 更多