node.js - Mongoose 和 NodeJS 项目的文件结构

标签 node.js mongoose

目前,我的 Mongoose/NodeJS 应用程序的/models/models.js 文件中有我的所有模型(架构定义)。

我想将它们分成不同的文件,例如:user_account.js、profile.js 等。但是我似乎无法这样做,因为我的 Controller 中断并报告“找不到模块”一旦我把这些类分开。

我的项目结构如下:

/MyProject
  /controllers
    user.js
    foo.js
    bar.js
    // ... etc, etc
  /models
    models.js
  server.js

我的 models.js 文件的内容如下所示:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

mongoose.connect('mongodb://localhost/mydb');

var UserAccount = new Schema({
    user_name       : { type: String, required: true, lowercase: true, trim: true, index: { unique: true } }, 
    password        : { type: String, required: true },
    date_created    : { type: Date, required: true, default: Date.now }
}); 

var Product = new Schema({
    upc             : { type: String, required: true, index: { unique: true } },
    description     : { type: String, trim: true },
    size_weight     : { type: String, trim: true }
});

我的 user.js 文件( Controller )如下所示:

var mongoose    = require('mongoose'), 
    UserAccount = mongoose.model('user_account', UserAccount);

exports.create = function(req, res, next) {

    var username = req.body.username; 
    var password = req.body.password;

    // Do epic sh...what?! :)
}

如何将架构定义分解为多个文件并从我的 Controller 中引用它?当我确实引用它时(在架构位于新文件中之后)我收到此错误:

*错误:尚未为模型“user_account”注册架构。*

想法?

最佳答案

这是一个示例 app/models/item.js

var mongoose = require("mongoose");

var ItemSchema = new mongoose.Schema({
  name: {
    type: String,
    index: true
  },
  equipped: Boolean,
  owner_id: {
    type: mongoose.Schema.Types.ObjectId,
    index: true
  },
  room_id: {
    type: mongoose.Schema.Types.ObjectId,
    index: true
  }
});

var Item = mongoose.model('Item', ItemSchema);

module.exports = {
  Item: Item
}

要从 app/controllers/items.js 中的项目 Controller 加载它 我会这样做

  var Item = require("../models/item").Item;
  //Now you can do Item.find, Item.update, etc

换句话说,在模型模块中定义模式和模型,然后只导出模型。使用相对的 require 路径将模型模块加载到 Controller 模块中。

要建立连接,请在服务器启动代码(server.js 或其他)中尽早处理。通常你会希望从配置文件或环境变量中读取连接参数,如果没有提供配置,则默认为开发模式 localhost。

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost');

关于node.js - Mongoose 和 NodeJS 项目的文件结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9230932/

相关文章:

javascript - Mongoose - 当从集合中返回所有项目(没有搜索参数)时,从集合中返回的项目不包含其 mongo _id

javascript - 在 Node.js 中使用 WriteStream 写入文件时出现编码错误

node.js - 使用 Node 和 Heroku 进行负载平衡

node.js - 在nodejs中在不同路径但相同端口上打开websocket时出现EADDRINUSE错误

javascript - 将带有 Promise 的函数从 JS 转换为 TS 时出现问题

node.js - 使用 req.query.property 时出现“限制必须指定为数字”错误

node.js - 如何修复错误:only absolute URLS are supported in react ssr graphql

node.js - 用于时间跟踪的 MongoDB 架构设计

node.js - NodeJS API : Find a document into a collection by "Id" property , 在 Mongodb 中默认不是 "_id"

javascript - 忽略在 Mongoose 的 Find 函数的查询对象参数中传递的未定义值?