首页 > 解决方案 > 猫鼬找到返回空数组,即使它们是数据库上的值

问题描述

我正在尝试将商品数据添加到我的 stockrecord 集合中,如果商品名称已经在 stockrecord 集合中,我只想将商品数量的数量添加到我的 stockrecord 数量中。

但即使它们是现有数据,find 方法也返回一个空数组

这是我的代码

  commodity.map(async (e) => {
    const data = await new Commodity({
      name: e.commodityName,
      units: e.units,
      quantity: e.quantity,
    });
    data.donator = donator;
    await data.save();
    const stock = await StockRecord.find({
      name: {
        $eq: e.commodityName,
      },
    });
    //console.log(stock);

    if (stock.length === 0) {
      const record = await new StockRecord({
        name: e.commodityName,
        units: e.units,
        quantity: parseFloat(e.quantity),
      });
      await record.save();
      console.log(record);
    } else {
      console.log('may sulud');

      stock[0].quantity += parseFloat(e.quantity);
      await stock[0].save();
    }
  });

这是我的 stockrecord模型

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    const stockRecordSchema = new Schema({
      name: {
        type: String,
      },
    
      units: {
        type: String,
        enum: \['kg', 'pcs'\],
      },
      quantity: {
        type: Number,
      },
    });

标签: javascriptmongodbmongoose

解决方案


Array.map 不接受承诺

尝试使用for (const item of commodity) { //async magic here }


推荐阅读