Tharinda Hashen
Tharinda Hashen

Reputation: 81

How to Update many elements in mongoose array which has embedded documents

I have this mongoose model

resourceId: {
    type: String,
},

resourceName: {
    type: String,
},

dateAndValue: [
    {
        date: { type: Date },
        value: { type: Number },
    },
],

project: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'project',
},

I want to update all value fileds of dateAndValue array elemets to "0" of a given resourceId, given project within a given date range!

await QuantumResourcesManpowerAdmin.updateMany(
    {
        project,
        resourceId,
        'dateAndValue.date': { $gte: startDate, $lte: endDate },
    },
    {
        $set: {
            'dateAndValue.$.value': 0,
        },
    },
    { upsert: true }
);
res.status(200).json({ success: true });

This is the code I used for it. It returns success but does not do any update. All inputs are correct, something is wrong with only the updateMany query, all other functions work!

Upvotes: 0

Views: 822

Answers (1)

ArunOnly1
ArunOnly1

Reputation: 21

await QuantumResourcesManpowerAdmin.updateMany(
    {
        project,
        resourceId,
        'dateAndValue.date': { $gte: startDate, $lte: endDate },
    },
    {
        $set: {
            'dateAndValue.$[element].value': 0,
        },
    },
 {arrayFilters:[{'element.date':{$gte: startDate, $lte: endDate }}] ,upsert: true }
);
res.status(200).json({ success: true });

Upvotes: 0

Related Questions