繁体   English   中英

无法返回值以使用mongoose / mongodb和nodejs进行响应

[英]Cannot return values to response with mongoose/mongodb and nodejs

我通过Mongoose使用Nodejs,ExpressJs,MongoDB。 我创建了一个简单的UserSchema。 我将代码分成多个文件,因为我预见它们会变得复杂。

url'/ api / users'被配置为调用'routes / user.js'中的列表函数,这如预期的那样发生。 UserSchema的list函数确实被调用,但是它无法将任何内容返回给调用函数,因此不会有结果。

我究竟做错了什么 ?

我尝试根据http://pixelhandler.com/blog/2012/02/09/develop-a-restful-api-using-node-js-with-express-and-mongoose/对它进行建模

我想我对userSchema.statics.list的函数定义做错了

app.js

users_module = require('./custom_modules/users.js'); // I have separated the actual DB code into another file
mongoose.connect('mongodb:// ******************');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback() {
    users_module.init_users();
});

app.get('/api/users', user.list);

custom_modules / users.js

function init_users() {
    userSchema = mongoose.Schema({
        usernamename: String,
        hash: String,
    });

    userSchema.statics.list = function () {
        this.find(function (err, users) {
            if (!err) {
                console.log("Got some data"); // this gets printed 

                return users; // the result remains the same if I replace this with return "hello" 
            } else {
                return console.log(err);
            }
        });
    }

    UserModel = mongoose.model('User', userSchema);
} // end of init_users

exports.init_users = init_users;

路线/ user.js的

exports.list = function (req, res) {
    UserModel.list(function (users) {
        // this code never gets executed
        console.log("Yay ");

        return res.json(users);
    });
}

实际上,在您的代码中,您正在传递一个回调,该回调从未在函数userSchema.statics.list处理。

您可以尝试以下代码:

userSchema.statics.list = function (calbck) {    
  this.find(function (err, users) {
    if (!err) {        
      calbck(null, users); // this is firing the call back and first parameter should be always error object (according to guidelines). Here no error, so pass null (we can't skip)
    } else {    
         return calbck(err, null); //here no result. But error object. (Here second parameter is optional if skipped by default it will be undefined in callback function)
      }
    });    
 }

因此,您应该更改传递给此函数的回调。

exports.list = function (req, res){
UserModel.list(function(err, users) {
   if(err) {return console.log(err);}
   return res.json(users);
  });
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM