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


i trying simple function node.js , mongoose returns true if model empty.

the mongoose configuration 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 tried this:

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

and works fine, logs true, or false.

then tried do:

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

and again works fine, logs true or false, buy if do:

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

then log prints "undefined". can if need function returns true or false things this:

if (isusersempty2()) {} //do here...  

and isusersempty2() returns undefined.

isusersempty2() returns promise , means can't log did. need send response function. 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*/} }); 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -