cbn*_*bnz 6 mongoose mongodb node.js
我有四个猫鼬模型SoleTrader
,Partnership
、Company
和Trust
。它们足够不同,我无法将它们全部合并到一个模式中,但又足够相似,以至于我经常需要同时查询或更改所有 4 种类型,而很少关心它们是哪种类型。
有没有办法做到这一点——可能是将所有四种类型放在一个集合中——而不必每次都进行四次数据库调用?
由于您正在使用mongoose-schema-extend
,似乎您可以创建一个简单的“基本”架构并在此基础上扩展您的其他架构。如果要搜索所有这些,请使用基本模型。
例如:
// base schema
var PersonSchema = new Schema({
name : String
}, {
collection : 'users', // everything will get saved in the same collection
discriminatorKey : '_type'
});
// two schema's that extend off it
var EmployeeSchema = PersonSchema.extend({ department : String });
var EmployerSchema = PersonSchema.extend({});
// materialize all three into models
var Person = mongoose.model('Person', PersonSchema);
var Employee = mongoose.model('Employee', EmployeeSchema);
var Employer = mongoose.model('Employer', EmployerSchema);
...
// create some people
new Employee({
name : 'Homer Simpson',
department : 'Safety'
}).save(...);
new Employer({
name : 'Charles Montgomery Burns',
}).save(...);
...
// search across employers and employees
Person.find({ ... }, function(err, people) {
...
});
Run Code Online (Sandbox Code Playgroud)
但是,我不得不说的是,广告的行为的find()
根据鉴别键返回正确的模型实例并不为我工作。