Node.js: Module does not recognize Schema

若如初见. 提交于 2019-12-12 02:44:55

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/8127247/node-js-module-does-not-recognize-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!