我正在尝试在Express应用程序中使用Mongoose的继承,我的起点是this discussion on GitHub,在那里他们讨论如何实现该功能。
我的模型很简单:一个抽象的BookableAbstractSchema架构,以及一个扩展Bookable的MeetingRoom架构。
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var util = require('util');
// Define our user schema
var BookableAbstractSchema = function (){
Schema.apply(this,arguments);
this.add({
spaceId: {type: mongoose.Schema.Types.ObjectId, ref: 'Space'},
name: {
type: String,
required: true
}
});
}
util.inherits(BookableAbstractSchema, Schema);
var BookableSchema = new BookableAbstractSchema();
var bookable = mongoose.model('bookable', BookableSchema);
// MEETING ROOM
var MeetingRoomSchema = new BookableAbstractSchema({
something:String
});
var meetingRoom = bookable.discriminator('MeetingRoom', MeetingRoomSchema);
module.exports.MeetingRoom = meetingRoom;
在那之前它很有效。
当我想将每个Schema放在自己的文件中时,我有很多困难
bookable.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var util = require('util');
// Define our user schema
var BookableAbstractSchema = function (){
Schema.apply(this,arguments);
this.add({
spaceId: {type: mongoose.Schema.Types.ObjectId, ref: 'Space'},
name: {
type: String,
required: true
}
});
}
util.inherits(BookableAbstractSchema, Schema);
var BookableSchema = new BookableAbstractSchema();
module.exports= mongoose.model('bookable', BookableSchema);
meetingroom.js
var mongoose = require('mongoose');
var Bookable = require('./bookable');
var MeetingRoomSchema = new Bookable({
something:String
});
module.exports = Bookable.discriminator('MeetingRoom', MeetingRoomSchema); // error described below is thrown here.
但是我在控制台中收到以下错误:
throw new Error("You must pass a valid discriminator Schema");
当我调试时,'MeetingRoom'确实是model
的实例,而不是schema
这是我迷路的地方,我需要帮助:)为什么这一切都在同一个文件中,而不是模型在不同的文件中分开?
答案 0 :(得分:2)
MeetingRoomSchema
实际上必须属于mongoose.Schema
类型,而不是新的Bookable
对象。
以下是mongoose源代码中的相关验证:
if (!(schema instanceof Schema)) {
throw new Error("You must pass a valid discriminator Schema");
}
引用的
因此,MeetingRoomSchema
应定义如下:
var MeetingRoomSchema = new mongoose.Schema({
something: String
});
module.exports = Bookable.discriminator('MeetingRoom', MeetingRoomSchema);
希望这有帮助!