Javascript 为什么使用mongoose.save()函数会引发错误?

Javascript 为什么使用mongoose.save()函数会引发错误?,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,此函数在product.save()不是函数的情况下抛出错误,我无法找出原因。也许我调用increaseStock时出现了一个错误,也许这就是导致函数失败的原因 const increaseStock = async (productId, quantity, price, creator) => { try { const product = await Product.find({ name: productId, creator: creator }); if (

此函数在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);
  }
};
等待产品。查找(…
返回一个文档数组,这样
Product
上就没有方法
save()
。看起来您需要的是方法。类似于:

const product = await Product.findOne({ name: productId, creator: creator });
等待产品。查找(…
返回一个文档数组,这样
Product
上就没有方法
save()
。看起来您需要的是方法。类似于:

const product = await Product.findOne({ name: productId, creator: creator });

谢谢你这么多有用的东西,我没有意识到我在用。find代替。findOne。谢谢你这么多有用的东西,我没有意识到我在用。find代替。findOne。