【问题标题】:Express Mongoose Model.find() returns undefinedExpress Mongoose Model.find() 返回 undefined
【发布时间】:2016-06-28 00:22:37
【问题描述】:

嘿嘿,有问题。尝试发送包含 Mongo 数据的 Express 响应。
这是来自我的 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
});


这是单独文件中的猫鼬模型

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
    });
}

如何正确地从 getAllTask​​s 函数发送数据?

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    我相信您需要做的是 return getAllTasks 函数中的文档,但也许是使用回调异步执行此操作的更好方法,如下所示:

    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 static,在这种情况下,您的模型会看起来像这样:

    TaskSchema.statics.getAllTasks = function (callback) {
      return this.find().lean().exec(callback);
    }
    

    【讨论】:

    • 非常感谢!!!!简短、清晰、严格。现在我明白了我的错误在哪里
    • 没问题,很高兴我能帮上忙。
    【解决方案2】:

    这看起来是正确的,但是您忘记了 Javascript 的异步行为 :)。当您编写此代码时:

    module.exports.getAllTasks = function(){
            Task.find().lean().exec(function (err, docs) {
            console.log(docs); // returns json
        });
    }
    

    您可以看到 json 响应,因为您在回调内部使用了 console.log 指令(您传递给 .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() 函数,因为真正返回您想要的数据的东西是在回调内部...

    所以,要让它工作,你需要这样的东西:

    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)
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-20
      • 2021-10-22
      • 2021-08-08
      • 1970-01-01
      • 2013-11-23
      • 2015-02-07
      • 2020-09-09
      • 1970-01-01
      相关资源
      最近更新 更多