Mongoose Discriminator:NodeJS / Express

时间:2018-03-13 13:19:46

标签: node.js mongodb mongoose discriminator

我使用Express开发了CRUD API,在其中一个Create API中,我希望根据请求体中提供的布尔标志扩展我的Mongoose Model Schema。

创建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');

1 个答案:

答案 0 :(得分:0)

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;