我已经使用 Express 和其中一个 Create API 开发了 CRUD API,我希望根据请求正文中提供的 bool 标志扩展我的 Mongoose 模型架构。
创建API主体(需要以这种格式存储在数据库中):
{
"name" : "John Doe",
"admin" : true,
"adminControl1" : "Some Control",
"adminControl2" : "Some Other Control",
}
但是存储在我的MongoDB中的数据如下:
{
"name" : "John Doe",
"admin" : "true",
}
我的模型文件如下:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var options = { discriminatorKey: 'admin' }
var userSchema = new Schema({
name: {
type: String,
required: true
}
}, options);
const Event = mongoose.model('Event',userSchema);
const addedSchema = new mongoose.Schema({
adminControl1 : {
type: String
},
adminControl2 : {
type: String
},
},options);
const addedSchemaEvent = Event.discriminator(true,addedSchema);
module.exports = mongoose.model('Users', userSchema,'users');
最佳答案
Event.discriminator("Event2", addedSchema);
鉴别器的第一个参数是新的模型名称
这是我的模型的一个例子
let Area: any = mongoose.model("Area", areaSchema);
let Country: any = Area.discriminator("Country", countrySchema);
let City: any = Area.discriminator("City", citySchema);
module.exports = {
Area: Area,
Country: Country,
City: City,
};
其中areaSchema是基本schema,countrySchema和citySchema是添加的schema
然后我像这样导入模型
const Area_ = require("../models/Area");
const Area = Area_.Area;
const City = Area_.City;
const Country = Area_.Country;
关于node.js - Mongoose 鉴别器 : NodeJS/Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49257266/