【问题标题】:Express.js: the best way to populate mongodb table on startExpress.js:在启动时填充 mongodb 表的最佳方式
【发布时间】:2019-03-29 08:40:47
【问题描述】:

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

我的主要想法:我有一个像 Dictionary 这样的表(因此,如果该表中没有值,一些键:值应该在开始时预填充一次)。

我有两个模型:

MaintenanceMaintenanceType

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


    【解决方案1】:

    看看这个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 => {
    
                });
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多