Express Mongoose Model.find()返回undefined
Hej,有问题。 尝试使用Mongo数据发送快速响应。
这是我的Express服务器的代码
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 });
这是单独的文件中的mongoose模型
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
你的getAllTasks
函数中的文档,但也许更好的方法是使用如下所示的callbackasynchronous执行:
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) }); }
然后在你的路线,你会做的:
app.get('/get-all-tasks',function(req,res){ Task.getAllTasks(err, docs){ if(err) return res.json(error: err) res.json(msg: docs); } });
我不确定getAllTasks
应该是一个mongoose静态 ,在这种情况下,你的模型看起来像这样:
TaskSchema.statics.getAllTasks = function (callback) { return this.find().lean().exec(callback); }
这看起来是正确的,但是你忘记了JavaScript的asynchronous行为:)。 当你编码这个:
module.exports.getAllTasks = function(){ Task.find().lean().exec(function (err, docs) { console.log(docs); // returns json }); }
您可以看到json响应,因为您使用的是console.log
指令INSIDEcallback(您传递给.exec()的匿名函数)但是,当您键入:
app.get('/get-all-tasks',function(req,res){ res.setHeader('Content-Type', 'application/json'); console.log(Task.getAllTasks()); //<-- You won't see any data returned res.json({msg:"Hej, this is a test"}); // returns object });
Console.log
将执行getAllTasks()
函数,它不会返回任何东西(未定义),因为真正返回所需数据的是INSIDEcallback。
所以,为了得到它的工作,你需要这样的东西:
module.exports.getAllTasks = function(callback){ // we will pass a function :) Task.find().lean().exec(function (err, docs) { console.log(docs); // returns json callback(docs); // <-- call the function passed as parameter }); }
我们可以写:
app.get('/get-all-tasks',function(req,res){ res.setHeader('Content-Type', 'application/json'); Task.getAllTasks(function(docs) {console.log(docs)}); // now this will execute, and when the Task.find().lean().exec(function (err, docs){...} ends it will call the console.log instruction res.json({msg:"Hej, this is a test"}); // this will be executed BEFORE getAllTasks() ends ;P (because getAllTasks() is asynchronous and will take time to complete) });