更新指定的属性而不重新传递整个对象mongodb

时间:2016-05-21 06:28:35

标签: javascript node.js mongodb mongoose

module.exports.updateProduct = function(product_id,product,callback){
    var update = {
        name: product.name,
        image: product.image,
        description: product.description,
        price: product.price,
        discount_price: product.d_price,
        category_id: product.category_id,
        user_id: product.user_id
    }

    Products.findOneAndUpdate({"_id":product_id}, update ,{upsert: true,'new':true}, callback);
}

我看到了这段代码,我知道它的作用。它基本上更新了文档。但是,如果我想在不传递整个price对象的情况下更新例如update,那么这是可能的吗?

2 个答案:

答案 0 :(得分:1)

是的,可以使用$set运算符:

Products.findOneAndUpdate({"_id": product_id}, {$set: {price: product.price}}, opts);

答案 1 :(得分:0)

您可以使用$set来解决,例如:

Products.findOneAndUpdate({"_id":product_id}, {$set: {price: product.price}}, {new: true}, function (error, updateProduct) {
        // where {new: true} is option that is optional 
        if (error) {
            return callback(error, null); // if error return error and null as data in callback params
        }
        return callback(false, updateProduct); // return update product for success and false for error flag
    });
相关问题