是否可以在mongoose中拥有一组备用子文档架构?
例如,采用这个组成方案:如果我有一个人的主模式,并且我有一个名为vehicle类型的车辆的字段,我希望能够定义子文档模式,但是对于每种车辆类型(汽车) ,摩托车,自行车,公共汽车等等):
var car = new mongoose.Schema({
make: { type: String, required: true, default: 'Ford', trim: true },
model: { type: String, trim: true },
wheels: Number,
});
var motorbike = new mongoose.Schema({
make: { type: String, required: true, default: 'Honda', trim: true },
model: { type: String, trim: true },
seats: Number,
});
var bike = new mongoose.Schema({
make: { type: String, required: true, default: 'MuddyFox', trim: true },
model: { type: String, trim: true },
lights: Number,
});
var bus = new mongoose.Schema({
make: { type: String, required: true, default: 'MAN', trim: true },
model: { type: String, trim: true },
dents: Number,
});
/* person */
var person = new mongoose.Schema({
name: { type: String, required: true, default: 'Joe Bloggs', trim: true },
timeCreated: { type: Date, required: true, default: Date.now },
vehicles: [car, motorbike, bike, bus] /* this is what i want to do */
});
db.model('person', person);
请注意人员架构。
因此,该人可以拥有任何这些车辆,但每辆车的数据仍然可以根据自己的架构进行验证。
提前致谢
答案 0 :(得分:2)
有一个名为mongoose-schema-extend的mongoose插件,它允许你为Mongoose启用Schema继承,基本上我认为,你正在寻找这个功能。
请检查github项目:
您可以创建Vehicle
架构,将其作为数组添加到Person
架构,并为不同类型的车辆扩展Vehicle
。
答案 1 :(得分:1)
我无法找到任何多个嵌入文档作为数组传递的示例。
也许你可以重新安排这样的事情:
var car = new mongoose.Schema({
make: { type: String, required: true, default: 'Ford', trim: true },
model: { type: String, trim: true },
wheels: Number,
});
var motorbike = new mongoose.Schema({
make: { type: String, required: true, default: 'Honda', trim: true },
model: { type: String, trim: true },
seats: Number,
});
var bike = new mongoose.Schema({
make: { type: String, required: true, default: 'MuddyFox', trim: true },
model: { type: String, trim: true },
lights: Number,
});
var bus = new mongoose.Schema({
make: { type: String, required: true, default: 'MAN', trim: true },
model: { type: String, trim: true },
dents: Number,
});
var transport = new mongoose.Schema({
car: [car],
motorbike: [motorbike],
bike: [bike],
bus: [bus]
});
/* person */
var person = new mongoose.Schema({
name: { type: String, required: true, default: 'Joe Bloggs', trim: true },
timeCreated: { type: Date, required: true, default: Date.now },
vehicles: [transport]
});
db.model('person', person);
如果这不起作用,那么如this SO question中所述,您可以使用mongoose populate。添加deep population was added in Mongoose Deep 3.6后,此方法现在更有效。
所以你可以这样做:
var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
title : String,
fans : [{ type: Number, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
还有一个mongoose插件来帮助这个名为mongoose-deep-populate的功能,它是非常新的。