Express Mongoose Model.find()返回未定义 [英] Express Mongoose Model.find() returns undefined
本文介绍了Express Mongoose Model.find()返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,有问题.尝试发送包含Mongo数据的Express响应.
这是我的Express服务器中的代码
Hej, have a problem. Trying to send Express response with Mongo data in it.
This is code from my Express server
var Task = require('./modules/Task');
app.get('/get-all-tasks',function(req,res){
res.setHeader('Content-Type', 'application/json');
console.log(Task.getAllTasks()); // returns undefined
res.json({msg:"Hej, this is a test"}); // returns object
});
这是在单独文件中的猫鼬模型
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/todo-app');
var TaskSchema = mongoose.Schema({
name: String,
assignee: String
},{ collection : 'task' });
var Task = module.exports = mongoose.model('Task', TaskSchema);
module.exports.createTask = function (newTask, callback) {
newTask.save(callback);
}
module.exports.getAllTasks = function(){
Task.find().lean().exec(function (err, docs) {
console.log(docs); // returns json
});
}
如何正确地从getAllTasks函数发送数据?
推荐答案
我相信您需要做的是return
函数中的文档,但是也许是一种更好的方法,例如使用回调进行异步处理所以:
I believe what you would need to do is return
the docs in your getAllTasks
function, but perhaps a better way to do it asynchronously using callbacks like so:
module.exports.getAllTasks = function(callback){
Task.find().lean().exec(function (err, docs) {
// If there is an error, return the error and no results
if(err) return callback(err, null)
// No error, return the docs
callback(null, docs)
});
}
然后在您的路线内进行:
And then inside your route you would do:
app.get('/get-all-tasks',function(req,res){
Task.getAllTasks(err, docs){
if(err) return res.json(error: err)
res.json(msg: docs);
}
});
我不确定getAllTasks
是否应为猫鼬静态,哪种情况下,您的模型看起来应该像 这样:
I'm not sure if getAllTasks
should be a mongoose static, in which case your model would look something like this:
TaskSchema.statics.getAllTasks = function (callback) {
return this.find().lean().exec(callback);
}
这篇关于Express Mongoose Model.find()返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文