1
votes

When trying to update the date inside the MongoDB document, nothing is updated.

To update, I send a request to NodeJS like this:

collection.updateOne(
   { _id: ObjectId(...) },
   { $set: { 'field1.field2.0.date': new Date('2020-02-01T00:00:00Z') } },
   callback
)

The task uses the npm package [email protected] and MongoDB 3.6.20.

I tried to send the '2020-02-01T00:00:00Z' as a value - it is not updated. I tried to update the database version - it didn't help. I tried to update the driver version - it didn't help.

It is interesting that such a request goes through Robo3T and updates the value correctly.

enter image description here

Could you please tell me how to update the date inside the document for MongoDB?


UPD: Structure of document

const document = {
    field1: {
        exp: 1,
        field2: [
            {
                name: "test",
                date: 2019-10-01 00:00:00.000Z
            }
        ]
    },
    settings: {
        sharedTill: 2022-10-01 00:00:00.000Z
    },
    updatedBy: 'Vadim Prokopchuk'
}

UPD2: Added Response from MongoDB

MongoDB returned data and does not return an error.

enter image description here

1
can you show the structure of document (all fields)? - mangusta
have you tried putting some logs into callback? most probably the error is dropped (for some reason) and the document is not updated. the document structure is fine - mangusta

1 Answers

1
votes

the syntax you're using isn't correct. Refer the query below, it would work

collection.updateOne(
   { _id: ObjectId(...) , 'field1.field2.name':"test"},
   { $set: { 'field1.field2.$.date': new Date('2020-02-01T00:00:00Z') } },
   callback
)

Here, we are finding the element of the array which matches our condition and then updating the date of that particular element of the array.