目前我所有的模型(模式定义)都在/models/models中.我的Mongoose/NodeJS应用程序的js文件.

我想把它们分成不同的文件,比如:user_account.js,个人资料.然而,当我把这些类分开后,我的控制器中断并返回"cannot find module"时,我似乎不能这样做.

我的项目 struct 如下:

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

我模型的内容.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 }
});

我的用户.js文件(控制器)如下所示:

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?! :)
}

如何将模式定义分解为多个文件,并从控制器引用它?当我引用它时(模式在新文件中之后),我会出现以下错误:

*错误:尚未为模型"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中从项目控制器加载这个,我会这样做

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

换句话说,在模型模块中定义模式和模型,然后只导出模型.使用相对路径将模型模块加载到控制器模块中.

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

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

Node.js相关问答推荐

NPM:一般的npm二进制依赖可以静态构建吗?

如何在Firebase Cloud Function v2计划函数中设置代码中的时区?

购物车是空的状态|本地存储不更新产品数量|Redux|

MongoDB的方面查询的Postgres类似功能

如何防止Socket-io实例化React/Next.js中的两个套接字(当前在服务器*和*客户端实例化)

在 TypeScript 中正确键入 MongoDB find 方法

PEAN auth 应用程序:为什么 Angular 拦截器总是使用BehaviorSubject 返回 null(即初始值),而不是更新后的值?

使用单个 MongoDB 查询更新多个元素

我如何在nodejs中的路由之间交换令牌

如何在 Firestore 函数上使用类型模型来获取字段值

Solidity 将数据位置从内存更改为存储

找不到模块bcryptjs

处理 UTC 日期和future

如何从动态Typescript 文件加载模块

Electron 模板(Typescript + Webpack)中的这个 Electron Forge ERROR 是什么?

是Electron 的密码和登录凭据的安全存储吗?

这到底是什么';拒绝未经授权';对我来说是什么意思?

Node.js 表达的 Error 对象expose 了哪些属性?

JSHint 是否支持异步/等待?

什么是 JavaScript 中的REPL?