mongoose: Model.update with $rename does not seem to work
note: I’m using 3.8.33, so if this is resolved in 4.x my apologies, I’m not able to upgrade the project I’m working on yet…
I’ve got a field in a collection that I want to rename, and have been able to do it successfully from the mongo
cli using the following:
db.agents.update({}, { $rename: { "state": "contactStatus" } }, { multi: true })
However, I want to write this into an update script so it is applied to my staging and production environments when the new version of my app is released.
Since I’m using mongoose, it seems I should be able to use the Model.update
method to achieve the same:
AgentModel.update(
{ },
{ $rename: { state: 'contactStatus' } },
{ multi: true },
function(err, raw) { console.log(err, raw); }
);
This doesn’t seem to have any effect on the data, however, and the value of raw
when logged to the console is 0
.
Should this update query be supported by Mongoose? I know that the update
query is rewritten to { $set: { update } }
when overwrite: false
(default), but the docs say:
All top level keys which are not atomic operation names
… which I had expected would mean $rename
would work as expected.
Not sure if this is related to #3027? No error is being thrown.
Any guidance would be appreciated, and if there’s further debug information I can provide please let me know.
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Comments: 27 (4 by maintainers)
Commits related to this issue
- test(query): repro #3171 — committed to Automattic/mongoose by vkarpov15 8 years ago
Try doing
db.User.update({}, { $rename: { hashedPassword: 'password' } }, { multi: true, strict: false }, function(err, blocks) { });
. I presumehashedPassword
is not defined in your schema so mongoose will strip that out by default unless you dostrict: false
Mongoose was deleting the field from my
$rename
query since I already renamed the field in the Schema. So I used{strict: false}
, that way it works withModel.update
. I would think this should be the default behavior, since we’re not planning on leaving both fields in the Schema.P.S. works well with
Model.collection.update
but that’s deprecated.