简体   繁体   中英

Node.js: Module does not recognize Schema

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM