在猫鼬中动态创建mongo集合。我尝试了以下代码:建议我
function residenceModel(regionName){
const residenceSchema = new Schema({
key:String,
value:String
}, { strict: false });
return mongoose.model(
`residence_meta_${regionName}`,
residenceSchema,
`residence_meta_${regionName}`
);
}
console.log(residenceModel);
exports.ResidenceModel = residenceModel;
答案 0 :(得分:0)
您可以通过以下简单步骤创建动态模型
创建文件dynamicModel.js
const mongoose = require('mongoose')
//import mongoose from 'mongoose'
const Schema = mongoose.Schema
const dynamicModel = (regionName) => {
const residenceSchema = new Schema({
key:String,
value:String
}, { strict: false })
return mongoose.model(
`residence_meta_${regionName}`,
residenceSchema,
`residence_meta_${regionName}`
);
}
module.exports = { dynamicModel }
// export default { dynamicModel }
在要包含或创建模型的文件上,假设app.js
// Please take care of path
const { dynamicModel } = require("./dynamicModel")
//import { dynamicModel } from "./dynamicModel";
.....
.....
// User this method to create model and use It
const countryModel = dynamicModel("country")
countryModel.create({ key:"country", value:"USA" });
多次使用此方法,试一下,让我知道
答案 1 :(得分:0)
我解决了这个问题。下面是代码。你们可以使用它。
function createMetaCollection(regionName){
console.log(regionName);
var residenceSchema = new Schema({
region:String,
customer_type:String,
},{strict: false});
residenceSchema.plugin(autoIncrement.plugin,{model:'resident_meta_'+regionName,field:regionName+'id',startAt:1});
exports.Typeof_employment_meta = mongoose.model('resident_meta_'+regionName,residenceSchema,'resident_meta_'+regionName);
}