简体   繁体   中英

Want to check if user already exist MongoDB

my promise always reject even tho the _name i pass in parameters is not always the same as one in the collection any help would be much appreciated Thanks!

  myCheckUser(_name) { var self = this; return new Promise((resolve, reject) => { self.db.collection("USER").find({ "username": _name }, { $exists: true }).toArray(function (err, doc) //find if a value exists { console.log("DOC USERNAME: " + doc.username); if (doc) //if it does { reject("Found user"); console.log(doc.username); // print out what it sends back } else // if it does not { console.log("Not in docs"); resolve("Not found continue logic!") } } ) }); }; 

You have to resolve the promise if data is found and reject the promise. I have corrected your code below:

  myCheckUser(_name) { var self = this; return new Promise((resolve, reject) => { self.db.collection("USER").find({ "username": _name }, { $exists: true }).toArray(function (err, doc) //find if a value exists { if (doc && doc.length) //if it does { console.log(doc); // print out what it sends back resolve("Found user"); } else // if it does not { console.log("Not in docs"); reject("Not found continue logic!") } } ) 

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