javascript - 无法返回值以响应 mongoose/mongodb 和 nodejs

标签 javascript node.js mongodb mongoose

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

url '/api/users' 配置为调用 'routes/user.js' 中的列表函数,这按预期发生。确实调用了 UserSchema 的列表函数,但它无法向调用函数返回任何内容,因此没有结果。

我做错了什么?

我尝试根据 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;

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

关于javascript - 无法返回值以响应 mongoose/mongodb 和 nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18350615/

相关文章:

javascript - 如何使用 Node.js 在非常简单的 JS 文件中编辑对象

mongodb - everyauth,第一次登录有效,第二次失败

javascript - 如何在异步生成器函数中引发错误

Javascript:完成DOM操作时的事件

javascript - jQuery在php echo中动画div

java - 如何在 OSX 10.6 Snow Leopard 上最好地安装 Rhino

javascript - Node.js 代理请求并使用 AES 对其进行加密

javascript - 如何检查运行 Web 应用程序的设备

javascript - 使用 MongoJS 管理与 Mongo 的连接的正确方法是什么?

javascript - 在 Mongoose 中,如何根据相关集合中的值查找记录?