Node.js:模块无法识别架构 [英] Node.js: Module does not recognize Schema

查看:289
本文介绍了Node.js:模块无法识别架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

server.coffee 上,我有:

User = mongoose.model 'User', s.UserSchema

addEntryToCustomer = require './lib/addEntryToCustomer'

addEntryToCustomer.coffee 我有:

module.exports = (phone,res,req) -> 
    User.find {account_id: phone.account_id }, (err, user) ->

我收到此错误:

2011-11-14T19:51:44+00:00 app[web.1]: ReferenceError: User is not defined


推荐答案

在node.js中,模块在各自的上下文中运行。这意味着 User 变量在 addEntryToCustomer.coffee 中不存在。

In node.js, modules run in their own context. That means the User variable doesn't exist in addEntryToCustomer.coffee.

您可以使 User 成为全局用户(对此要小心):

You can either make User global (careful with it):

global.User = mongoose.model 'User'

将用户变量传递给模块:

Pass the user variable to the module:

module.exports = (User, phone, res, req) -> 
  User.find {account_id: phone.account_id }, (err, user) -> …

或重新加载模型:

mongoose = require 'mongoose'

module.exports = (phone,res,req) -> 
  User = mongoose.model 'User'
  User.find {account_id: phone.account_id }, (err, user) ->

也可以向模型本身添加方法,尽管在定义模式时需要这样做: http://mongoosejs.com/docs/methods-statics.html

It's also possible to add methods to the Models themselves, though you need to do that when defining the Schema: http://mongoosejs.com/docs/methods-statics.html

这篇关于Node.js:模块无法识别架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆