[英]Why does using mongoose .save() function throws me an error?
This function is throwing an error where product.save() is not a function and i cant figure out why.这个函数抛出一个错误,其中 product.save() 不是一个函数,我不知道为什么。 Maybe there is an error where i call increaseStock and mabye thats whats making the function fail?
也许在我调用 increaseStock 和 mabye 时出现错误,这就是使函数失败的原因?
const increaseStock = async (productId, quantity, price, creator) => {
try {
const product = await Product.find({ name: productId, creator: creator });
if (!product) {
const error = new Error('Could not find any product');
error.statusCode = 404;
throw error;
}
const newStock = parseInt(product.stock) + Number(quantity);
product.stock = newStock;
product.price = price;
product.finalPrice =
price + (Number(product.percentage) * Number(product.price)) / 100;
await product.save();
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
console.log(err);
}
The other function where this function is called is:调用此函数的另一个函数是:
exports.addPurchase = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const error = new Error('Validation failed, entered data is incorrect');
error.statusCode = 422;
throw error;
}
try {
const purchase = new Purchase({
description: req.body.description,
ticketType: req.body.ticketType,
ticketSerie: req.body.ticketSerie,
ticketNumber: req.body.ticketNumber,
total: req.body.total,
details: req.body.details,
creator: req.groupId,
supplier: req.body.supplier
});
let details = req.body.details;
await details.map(async detail => {
await increaseStock(detail.product, Number(detail.quantity), Number(detail.price), req.groupId);
});
await purchase.save();
res.status(200).json({
message: 'Purchase created.',
purchase: purchase
});
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}
};
await Product.find(...
返回一个文档数组,因此product
上没有save()
方法。看起来您需要的是findOne()方法。例如:
const product = await Product.findOne({ name: productId, creator: creator });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.