如何在 mongoDb 中初始化猫鼬模式?

How to initialise mongoose schema in mongoDb?

我想为 node.js 应用程序 startup/mongoose 连接到数据库的所有 schema/model 文件创建数据库和集合。 (不是为数据库播种,而是 initialise/set 数据库上的结构模式)

我的模特:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

// define the schema
var modelSchema = new Schema({
    appId: {
        type: String,
        indexed: true
    }
});

// export the Model
module.exports = mongoose.model('Model', modelSchema)

我正在使用这种方法连接到数据库:

mongoose.connect(mongodbUri, mongooseOptions);

目前,只有当我向数据库中插入内容时,mongoose 才会在数据库中创建模式。

如果您在架构中将 indexed 固定为 index,这将最终创建您的集合,以便在您创建模型时也可以创建其索引。