Mongoose update 'cannot use the part (..) to traverse the element

前端 未结 2 1520
清歌不尽
清歌不尽 2020-12-11 00:43

I have this really annoying issue where i can\'t update anything using mongoose. It\'s really frustrating to use, and the documentation is not helping at all.

I have

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 01:15

    Try to use the positional $ operator in the update which identifies an element in an array to update without explicitly specifying the position of the element in the array, but this will only ever match one element at a time:

     User.update(
        { 
            "local.email": user,
            "devices.id": { "$ne": deviceID },
            "devices.name": { "$ne": deviceName }
        }, 
        { 
            "$set": { 
                "devices.$.id": deviceID,
                "devices.$.name": deviceName 
            }
        } 
    );
    

    From the docs, the positional $ operator acts as a placeholder for the first element that matches the query document, and the array field must appear as part of the query document hence the query document

    "devices.id": { "$ne": deviceID },
    "devices.name": { "$ne": deviceName }
    

    contains the device array and will match those documents where the device array id is not equal to deviceID and the name is not the same as the name which you are trying to update. This will even match documents where the device array is empty.

提交回复
热议问题