[英]Node.js and mongodb TypeError: undefined is not a function
[英]TypeError: undefined is not a function in Node.js
在我的Group模型中,我正在導出一個函數,該函數使用回調傳遞查詢結果。
在我的路由器文件中,正確地需要另一個文件后,我正在調用此函數。
那是我的./models/groups.js
:
var groupSchema = new mongoose.Schema({
[...]
module.exports.getAll = function(cb) {
groupSchema.find({}, function(err, groups) {
if (err) return cb(err)
cb(null, groups)
})
}
[...]
module.exports = mongoose.model('Group', groupSchema);
那是我的./routes/groups.js
文件。
var Group = require('../models/group')
router.route('/groups')
.get(function(req, res, next) {
Group.getAll( function(err, group){
if (err) res.send(err)
res.send(group)
})
})
[...]
這是行不通的,因為每次我發出一個get請求時,我都會得到一個TypeError: undefined is not a function
錯誤。 我知道我可以直接在路由器文件上進行查詢,但是我認為將路由和方法之間的內容分開是一種更好的做法。
將新值分配給module.exports
時,將覆蓋定義getAll
函數的對象。
您有2個選擇:
使用getAll
函數擴展模型,然后像今天一樣導出。
基本上看起來像這樣:
var model = mongoose.model('Group', groupSchema); model.getAll = function(cb) { ... }; module.exports = model;
但這不是很“干凈”。
將模型導出到getAll
函數旁邊的命名屬性下。
基本上看起來像這樣:
module.exports.getAll = function(cb) { ... }; module.exports.model = mongoose.model('Group', groupSchema);
然后,在您的路線中,您將擁有:
var Groups = require('../models/group'); // Now you have Groups.getAll & Groups.model
總體而言,這更加靈活,可以讓您導出自己認為合適的其他類型/函數/值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.