我尝试使用mongoose-schema-extend为mongoDB子文档实现继承,稍后使用mongoose本身。 基本要求是在继承类中定义其他属性并在DB上获取它们 - 这在两种方法中都可以正常工作。 第二个要求是能够使用discriminatorType和instanceOf来区分类型。 discriminatorType没有使用mongoose-schema-extend保存在DB中,只直接使用mongoose discriminator。 instanceOf在两种情况下都不起作用(在parentDocument.find之后) - 口袋似乎只是对象。
mongoose-schema-extend的代码:
var PocketSchema = new mongoose.Schema({
name: {type: String, unique: true , required: true}, //required - not working within array
status: {type: String , enum :['ACTIVE','RETIRED'], Default:'ACTIVE' },
limits : ['Limit']
},{ discriminatorKey : '_type' });
dbConn.model('Pocket', PocketSchema);
var CreditCardPocketSchema =dbConn.models.Pocket.schema.extend({
PAN : {type: String, required: true }
});
dbConn.model('CreditCardPocket', CreditCardPocketSchema);
var customerSchema = mongoose.Schema({
username: {type: String, unique: true, required: true } ,
password: String,
email: { type: String },
status: {type: String , enum :['REGISTERED','ACTIVE','RETIRED'] , Default:'REGISTERED'},
pockets : ['Pocket']
});
使用util.extend进行mongoose的代码:
function PocketSchema() {
mongoose.Schema.apply(this, arguments);
this.add({
name: {type: String, unique: true , required: true},//required - not working within array
status: {type: String , enum :['ACTIVE','RETIRED'], Default:'ACTIVE' },
limits : ['Limit']
});
};
util.inherits(PocketSchema, mongoose.Schema);
var pocketSchema = new PocketSchema();
dbConn.model('Pocket', pocketSchema);
var CreditCardPocketSchema = new PocketSchema({
PAN : {type: String, required: true }
});
dbConn.models.Pocket.discriminator('CreditCardPocket', CreditCardPocketSchema);
**检查instanceOf的代码:**
exports.showPockets = function(req, res){
var username = req.params.username;
dbConn.models.Customer.findOne({username:username},function(err,user) {
if (user === null) {
res.send('user does not exist');
}else {
user.pockets[0] instanceof dbConn.models.CreditCardPocket;
user.pockets[0] instanceof dbConn.models.Pocket;
dbConn.models.Pocket.prototype.isPrototypeOf(user.pockets[0]);
dbConn.models.SVAPocket.prototype.isPrototypeOf(user.pockets[0]);
}
});
};
mongoose-schema-extend鉴别器是否对子文档无法正常工作?并且例如,不应该返回true?
提前致谢。