简体   繁体   中英

Find() function retunrs undefined - Mongoose and Node.js

I was trying to do a simple function with Node.js and Mongoose that returns true if the model is empty.

The mongoose configuration is fine:

var mongoose = require('mongoose');
var db = mongoose.createConnection( 'mongodb://localhost:27017/prueba' );

var userSchema = mongoose.Schema({
    phoneNumber: Number,
    name: String
});
var User = db.model('User', userSchema, 'User'');

Then I tried to do this:

User.find(function(err, data) {
    if (err) {console.log(err)};
    console.log(data.length == 0 );
});

And it works fine, it logs true, or false.

Then I tried to do:

var isUsersEmpty =  function () {
    User.find(function(err, data) {
        if (err) {console.log(err)};
        console.log(data.length == 0);
    });
}
isUsersEmpty();

And again it works fine, it logs true or false, buy if I do:

var isUsersEmpty2 = function () {
    User.find(function(err, data) {
        if (err) {console.log(err)};
        return data.length == 1;
    });
}
console.log(isUsersEmpty2());

Then the log prints "Undefined". What can I do if I need a function that returns true or false to do things like this:

if (isUsersEmpty2()) {} //Do something here... 

And isUsersEmpty2() returns always undefined.

isUsersEmpty2() returns a promise , which means you can't just log it like you did. You need to send a response from the function. This should work:

var isUsersEmpty2 = function (res) {
User.find(function(err, data) {
    if (err) res(err, null);
    res(null, data.length == 1);
});
}

isUsersEmpty2(function(err, res) {
   if(res) {/*do something*/}
});

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