【问题标题】:ExpressJS app structure with Mongoose Models带有 Mongoose 模型的 ExpressJS 应用程序结构
【发布时间】:2018-10-03 09:12:35
【问题描述】:

我想知道我的猫鼬模型在 ExpressJS 应用程序的上下文中应该放在哪里?我不想把所有东西都放到 server.js/coffee 中。有没有例子?

【问题讨论】:

    标签: express mongoose


    【解决方案1】:

    将它们放在一个名为 app/models 的目录中,并像下面这样构建您的应用程序:ExpressJS How to structure an application?

    【讨论】:

      【解决方案2】:

      我创建了一个 data/models.js 模块,用于导出我正在使用的各种模型。例如models.js:

      var mongoose = require("mongoose");
      mongoose.connect("localhost", "databaseName");
      
      var userSchema = mongoose.Schema({
        name: "string",
        email: "string",
        password: "string"
      });
      
      exports.User = mongoose.model("User", userSchema);
      

      这使我可以像这样在应用程序的其他地方要求模型:

      var mongoose = require("mongoose")
        , User = require("../data/models").User
      

      【讨论】:

        【解决方案3】:

        应该如下: 模型.js: module.exports = mongoose.model(“用户”, userSchema);

        Server.js: Const User = require(“../data/models”);

        【讨论】:

          猜你喜欢
          • 2014-05-22
          • 1970-01-01
          • 2012-01-15
          • 2023-03-12
          • 2015-12-02
          • 1970-01-01
          • 2010-12-05
          • 1970-01-01
          • 2019-04-08
          相关资源
          最近更新 更多