这个函数抛出一个错误,其中product.save()不是一个函数,我不明白为什么。也许我调用increaseStock时出现错误,也许这就是函数失败的原因?
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);
}
调用此函数的另一个函数是:
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 });
关于javascript - 为什么使用 mongoose .save() 函数会引发错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59348941/