Express.js:启动时填充mongodb表的最佳方法

时间:2018-10-24 20:17:44

标签: javascript node.js mongodb express mongoose

我从Ruby on Rails来到Node.js(Express.js)。在那里,通过迁移对db进行任何更改都非常容易。

我的主要想法:我有一个类似Dictionary的表(因此,如果此表中没有值,则应该在启动时预先填充一些key:values)。

我有两个模型:

MaintenanceMaintenanceType

Maintenance通过MaintenanceType使用ref

维护模式:

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动作的最佳位置吗?

1 个答案:

答案 0 :(得分:0)

看看这个What is the best method to seeding a Node / MongoDB application?。这可能会有帮助。

另一种方法是手动执行此操作,例如检查MaintenanceType集合中是否有项目,如果没有则插入初始值。看下面的代码。假设您正在使用get请求转到主页/索引页面。

routes.get('/', (request, response) => {
    let initialValues = [{name: 'wheels', isDefault: true}, {name: 'engine', isDefault: true}];

    MaintenanceType.find({}, (error, doc) => {
        if (doc.length === 0) {
            let maintenanceType = new MaintenanceType(initialValues);

            maintenanceType.save(error => {

            });
        }
    });
});