我在理解如何构造Mongoose模型文件时遇到了问题,因此在需要依赖项时我没有任何依赖关系。我有很多模型文件,当我需要另一个模型文件作为参考类型时,如果我不按顺序要求模型文件,则会遇到错误。如果由于依赖关系在模型文件列表中上下浮动而无法以线性顺序加载它们,则在架构上应该做些什么?我是否只需要把他们弄混,希望我不要把自己画在角落里还是我做错了?
app.js-我的应用顶部
const path = require('path');
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
const express = require('express');
require('./models/task');
require('./models/taskstory');
require('./models/majortask');
require('./models/majortaskinstance');
require('./models/client');
require('./models/discipline');
require('./models/disciplineinstance');
require('./models/estimate');
require('./models/project');
require('./models/user');
const taskstoryRoutes = require('./routes/taskstory');
const majortaskRoutes = require('./routes/majortask');
const taskRoutes = require('./routes/task');
const userRoutes = require("./routes/user");
const clientRoutes = require("./routes/client");
const projectRoutes = require("./routes/project");
const estimateRoutes = require('./routes/estimate');
const disciplineRoutes = require('./routes/discipline');
const app = express();
还有一个示例模型... Estimate.js
const mongoose = require('mongoose');
const disciplineinstanceschema = require('mongoose').model('disciplineInstance').schema;
var ObjectId = require('mongoose').Types.ObjectId;
const estimateScheme = mongoose.Schema({
estimatename: { type: String, required: true, unique: true },
summarytext: { type: String },
scopetext: { type: String },
disciplines:{type: [disciplineinstanceschema], sparse:true}
});
module.exports = mongoose.model('Estimate', estimateScheme);
答案 0 :(得分:0)
最好在路径文件中导入模型,并在其文件中导入每个模型依赖项,如下所示:
// models/disciplineInstance.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const disciplineInstanceSchema = new Schema({
// some things
});
module.exports.disciplineInstanceSchema = disciplineInstanceSchema; // schema
module.exports.DisciplineInstance = mongoose.model('DisciplineInstance', disciplineInstanceSchema); // model
// models/estimate.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const {DisciplineInstanceSchema} = require('models/disciplineInstance.js');
const estimateScheme = new Schema({
estimatename: { type: String, required: true, unique: true },
summarytext: { type: String },
scopetext: { type: String },
disciplinesByRef:{ // by reference model design
type: Schema.Types.ObjectId,
ref: 'DisciplineInstance' // this is a collection/model name
},
disciplinesEmbedded: { // embedded model design
type: DisciplineInstanceSchema
}
});
module.exports = mongoose.model('Estimate', estimateScheme);
embedded design
与reference design
的更多信息,请参见mongodb documents。