简体   繁体   中英

mongoose discriminator find query

I am trying to use a test case as described in "mongoose-schema-extend"

All is working just as explained there.

But, I would expect it to give me the ability to do a search query on the inherited type. So if we consider the example showed in the link above:

var VehicleSchema = mongoose.Schema({ 
  make : String,
}, { collection : 'vehicles', discriminatorKey : '_type' });

var CarSchema = VehicleSchema.extend({
  year : Number
});
var BusSchema = VehicleSchema.extend({
  route : Number
})

var Vehicle = mongoose.model('vehicle', VehicleSchema),
    Car = mongoose.model('car', CarSchema),
    Bus = mongoose.model('bus', BusSchema);

var accord = new Car({ 
  make : 'Honda',
  year : 1999
});
var muni = new Bus({
  make : 'Neoplan',
  route : 33
});

I would expect Car.find({}) to return only the documents which have _type : Car . Instead, I get all vehicles .

Is there a way to get only the cars except for doing Car.find{"_type":"Car"}) ?

You probably have to do a feature request for that to the package owner or do a pull request to the project yourself. A work-around, however, could be to implement a custom find method:

CarSchema.statics._find = function(query, next) {
    query._type = 'Car';
    this.find(query, next);
}

Car._find({}, function(err, cars) {
    ... 
};

The _find should now only return Car objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM