Node.js:模块不能识别Schema

Node.js: Module does not recognize Schema

本文关键字:识别 Schema 不能 模块 js Node      更新时间:2023-09-26

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中不存在。

您可以使User全局(小心使用它):

global.User = mongoose.model 'User'

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

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