当我在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);
}
});
});