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.