简体   繁体   中英

mongoose find returning empty array even their is a value on the database

I'm trying to add commodity data to my stockrecord collection and if the commodity name is already in the stockrecord collection I just want to add the quantity of the commodity quantity to my stockrecord quantity.

but even their is existing data the, find method is returning an empty array

This my code

  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();
    }
  });

This is my stockrecord model

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

Array.map does not accept Promises

Try using for (const item of commodity) { //async magic here }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM