[英]Mongoose Discriminator : NodeJS/Express
我已經使用Express開發了CRUD API,並且在其中一個Create API中,我希望基於請求正文中提供的布爾標志來擴展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是基本架構,countrySchema和citySchema是添加的架構
我像這樣導入模型
const Area_ = require("../models/Area");
const Area = Area_.Area;
const City = Area_.City;
const Country = Area_.Country;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.