My goal is to update commodity data in my stockrecord collection by adding the quantity of a commodity if it already exists in the collection.
However, I encountered an issue where the find method returns an empty array even for existing data.
Here is the code snippet:
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();
}
});
To understand more about my stockrecord model, check it out here:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const stockRecordSchema = new Schema({
name: {
type: String,
},
units: {
type: String,
enum: \['kg', 'pcs'\],
},
quantity: {
type: Number,
},
});