Mongoose的静态方法抛出:TypeError:Model.call没有方法' save'

时间:2015-09-07 03:13:28

标签: node.js mongodb mongoose

当我在Express中的路由中发送完全有效的JSON主体时,我得到以下与Mongoose中模型的静态方法相关的错误。

Product.save({
        ^
TypeError: Object function model(doc, fields, skipId){
bla bla bla ...
} has no method 'save'

我在Express中有以下路由功能:

function createNewProduct(req, res){
    // Check if the Merchant is authorized
    User.checkIfExists(req.body.key, function(isThere, user){
        // Check if username is valid
        if(isThere === true){
            // Check if he has merchant priveleges
            if(user.usertype == 'merchant'){
                // Check if all the product field are valid
                // TODO add a product parameter validator here

                // Generate a OriginID
                var originId = user.username + Date.now();

                // Save the product to the db
                Product.createNewProduct(originId, req.body, function(isItCreated, product){
                    if(isItCreated === true){
                        res.json(product);
                    } else {
                        res.json({
                            "error":"Problem in database!"
                        });
                    }
                });
            } else {
                res.json({
                    "error": "Not A Merchant"
                });
            }
        } else {
            res.json({
                "error": "Invalid Username"
            });
        }
    });
}

以下是Mongoose中createNewProduct static的实现:

// Static method for creating a product
productSchema.static('createNewProduct', function(originId, reqBody, callback){
    Product.save({
        "originId": originId,
        "name": reqBody.name,
        //image: { type: String },
        "merchant": reqBody.key,
        //shop: String,
        "description": reqBody.description,
        "cost": reqBody.cost,
        "availableNow": true
    }, function(err, product){
        if(err){
            console.log('Error creating new product');
            console.log(err);
            callback(false);
        } else {
            callback(true, product);
        }
    });
});

1 个答案:

答案 0 :(得分:0)

save是一个实例方法,因此您只能在Map<String, Integer> phoneDirectory = new java.util.HashMap<>(); 模型实例上调用它,而不能在模型本身上调用它。

要根据Product模型创建新文档并保存,请在模型上调用create

Product

或者,您可以单独创建一个新的Product.create({...}, function(err, product) {...}); 模型实例,然后在 上调用Product

save