Node.js:模块无法识别架构

发布于 2024-12-15 18:39:14 字数 469 浏览 0 评论 0原文

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

On server.coffee I have:

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

addEntryToCustomer = require './lib/addEntryToCustomer'

and on addEntryToCustomer.coffee I have:

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

And I get this error:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫腻 2024-12-22 18:39:14

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

您可以将 User 设为全局(小心):

global.User = mongoose.model 'User'

将用户变量传递给模块:

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

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

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) -> …

Or reload the model:

mongoose = require 'mongoose'

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文