【问题标题】:Mongo values not updatingMongo 值未更新
【发布时间】:2014-06-27 11:24:37
【问题描述】:

我试图简单地在猫鼬中增加一个对象的值,它似乎不想超过 2?有什么我想念的吗?我对 Mongo 还很陌生

campsite.findOne({slug : req.body.campsite.slug }, function(err, site){

    if(!site.tracking){
        console.log("no previous tracking at all");
        site.tracking = {};
    }

    if(site.tracking[req.body.tracking_type] == undefined){
        console.log("no previous tracking of this type");
        site.tracking[req.body.tracking_type] = 1;
    }else{
        console.log("well count it then!");
        site.tracking[req.body.tracking_type] += + 1;
    }

    site.save(function (err, fluffy) {
        console.log(err);
    });

    res.send(200);
});

它只是不会保存更新的结果?我的架构在下面

var campsitesSchema = new Schema({
    name: String,
    address_line_1: String,
    address_line_2: String,
    county: String,
    postcode: String,
    loc: Array,
    website: String,
    email: String,
    telephone_1: String,
    telephone_2: String,
    description: String,
    slug:String,
    status:String,
    confirm_url_key: String,
    password: String,
    short_description: String,
    long_description: String,
    features: Array,
    tracking: {}
});

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    使用带有 $inc 修饰符的更新会更好

    campsite.update({slug : req.body.campsite.slug }, {$inc: { 'tracking[' + req.body.tracking_type + ']' : 1} });
    

    【讨论】:

    • 你不能使用 'tracking[' + req.body.tracking_type + ']'
    • @user3240114 尝试“跟踪”。 + req.body.tracking_type
    • @user3240114 req.body.tracking_type 的值是多少?
    • 没关系,我已经整理好了,看来我能绕过它的唯一方法就是替换整个跟踪对象,看我的回答
    • 基本上我必须用 $set 修饰符替换整个对象,如果你没有回调它也不起作用
    猜你喜欢
    • 2022-12-15
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 2016-12-19
    • 2017-05-07
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多