Mongoose: FindOneAndUpdate Does Not Update An Existing Field
I am trying to fetch every minute a web API data to MongoDB, save it and update when there is any change. The problem is the volume(every field) field is updated only (happens afte
Solution 1:
If you want to update an element in an array, you can consider the positional operator: $ and add the field to your update query.
This identifies an element in an array to update based on a condition.
Example to update the embedded array with a volume
field equal to 100 and set to 200:
db.getCollection("collection").findOneAndUpdate({
id: 1,
"data.volume": 100
},
{ $set: { "data.$.volume": 200 }
});
Solution 2:
This solution was provided by srinivasy at the following link link
const creatStock = async (symbol, webApiData) => {
try {
// reversed array
const webApiDataReversed = webApiData.reverse();
const query = { symbol };
const position = await Stock.findOne(query);
if (!position) {
console.log('New stock'.green);
return Stock.create({
symbol,
data: webApiDataReversed,
});
}
await Stock.bulkWrite([
{
updateOne: {
filter: query,
update: { $pop: { data: 1 } },
},
},
{
updateOne: {
filter: query,
update: {
$addToSet: {
data: webApiDataReversed,
},
},
},
},
]);
} catch (ex) {
console.log(`creatStock error: ${ex}`.red);
}
};
Post a Comment for "Mongoose: FindOneAndUpdate Does Not Update An Existing Field"