gpt4 book ai didi

node.js - Mongoose的静态方法抛出: TypeError: Model.调用没有方法 'save'

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:34 24 4
gpt4 key购买 nike

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

最佳答案

save是一个实例方法,因此您只能在 Product 模型实例上调用它,而不能在模型本身上调用它。

要基于 Product 模型创建新文档并保存,请调用 create在模型上:

Product.create({...}, function(err, product) {...}); 

或者,您可以单独创建一个新的 Product 模型实例,然后调用save:

var product = new Product({...});
product.save(function(err, product) {...});

关于node.js - Mongoose的静态方法抛出: TypeError: Model.调用没有方法 'save',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32430582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com