【发布时间】:2019-03-29 08:40:47
【问题描述】:
我从 Ruby on Rails 来到 Node.js (Express.js)。在那里,通过迁移对 db 进行任何更改非常容易。
我的主要想法:我有一个像 Dictionary 这样的表(因此,如果该表中没有值,一些键:值应该在开始时预填充一次)。
我有两个模型:
Maintenance 和 MaintenanceType。
Maintenance 通过ref 使用MaintenanceType。
维护模式:
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const MaintenanceType = mongoose.model("MaintenanceType");
const maintenanceSchema = new mongoose.Schema(
{
number: {
type: String,
trim: true,
uppercase: true,
required: "enter a maintenance number"
},
maintenanceType: {
type: mongoose.Schema.ObjectId,
ref: "MaintenanceType"
},
description: {
type: String,
trim: true,
required: "enter a maintenance description"
}
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true }
}
);
maintenanceSchema.index({
number: "text"
});
module.exports = mongoose.model("Maintenance", maintenanceSchema);
MaintenanceType 模型:
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const maintenanceTypeSchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
required: "enter a maintenanceType name",
unique: "enter a unique maintenanceType name",
},
isDefault: {
type: Boolean,
default: false
}
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true }
}
);
// Define our indexes
maintenanceTypeSchema.index({
number: "text"
});
module.exports = mongoose.model("MaintenanceType", maintenanceTypeSchema);
start.js:
const mongoose = require("mongoose");
// import environmental variables from variables.env file
require("dotenv").config({ path: "variables.env" });
mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise;
mongoose.connection.on("error", err => {
console.error(`???? → ${err.message}`);
});
require("./models/MaintenanceType");
require("./models/Maintenance");
const app = require("./app");
app.set("port", process.env.PORT || 7777);
const server = app.listen(app.get("port"), () => {
console.log('started');
});
所以:启动服务器 -> 如果 'MaintenanceType' 表没有默认值 -> 添加一些默认值(如果不存在,例如:[{name: 'wheels', isDefault: true}, {name: 'engine', isDefault: true}])
我想到了app.listen 部分。但也许这不是放置.find 和.create bulk 操作的最佳位置?
【问题讨论】:
标签: javascript node.js mongodb express mongoose