简体   繁体   中英

Cannot return values to response with mongoose/mongodb and nodejs

I am using Nodejs, ExpressJs, MongoDB via Mongoose. I have created a simple UserSchema . I have my code separated into multiple files because I foresee them getting complex.

The url '/api/users' is configured to call the list function in 'routes/user.js' which happens as expected. The list function of UserSchema does get called, but it fails to return anything to the calling function and hence no result goes out.

What am I doing wrong ?

I tried to model it based on http://pixelhandler.com/blog/2012/02/09/develop-a-restful-api-using-node-js-with-express-and-mongoose/

I think I am doing something wrong with the function definition of 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);
    });
}

Actually in your code you are passing a callback, which is never handled in function userSchema.statics.list

You can try the following code:

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

Accordingly, you should change the callback which is passed to this function. ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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