Mongoose: Model.update is not updating the discriminator fields

Created on 1 Aug 2018  路  4Comments  路  Source: Automattic/mongoose

Do you want to request a feature or report a bug?
Feature

What is the current behavior?
I have two schemas something like below.

let UserSchema = new Schema({name: String, ...})
let User = mongoose.model('User', UserSchema);

let AdminSchema = new Schema({country:[String], ...}, {discriminatorKey: 'kind'}));
User.discriminator('Admin', AdminSchema);

I am trying to update the "Admin" doc by below code, but I am not able to update the field "country", which is present in the AdminSchema. Can we enhance the code to support this ?

User.update({ _id: '<>' }, {$set: {'country': 'India'}}, cb)

What is the expected behavior?
Expects to update the field "country" successfully

Please mention your node.js, mongoose and MongoDB version.
node: 6.11.3, mongoose: 4.11.14

Most helpful comment

FYI Using findOneAndUpdate on the result of a Base.discriminator in this particular case User.discriminator('Admin', AdminSchema); DOES NOT WORK , the way to use findOneAndUpdate to update discriminator documents is using the base model but specifying the discriminatorKey in the query parameter so :

const doc = await BaseModel.findOneAndUpdate( { _id: docId, discKey }, { $set: data }, { new: true } )

everything else failed for me , and this is not written in the docs

All 4 comments

Expected behavior, you need to do Admin.update({ _id: ... }, { $set: { country: 'India' } }), where const Admin = User.discriminator('Admin', AdminSchema);. The base User model doesn't know about the country field.

FYI Using findOneAndUpdate on the result of a Base.discriminator in this particular case User.discriminator('Admin', AdminSchema); DOES NOT WORK , the way to use findOneAndUpdate to update discriminator documents is using the base model but specifying the discriminatorKey in the query parameter so :

const doc = await BaseModel.findOneAndUpdate( { _id: docId, discKey }, { $set: data }, { new: true } )

everything else failed for me , and this is not written in the docs

@cdtuapp This is not working for me. Discriminator fields still remain untouched.

@adil-waqar please open a new issue and follow the issue template.

Was this page helpful?
0 / 5 - 0 ratings