使用es7 async / await检查文档是否存在于mongodb中
我试图检查用户提供的email
提供存在集合的users
,但我的函数不断返回未定义的每个调用。 我使用es6和async/await
,以摆脱大量的callback。 这是我的function(它是在一个类中):
async userExistsInDB(email) { let userExists; await MongoClient.connect('mongodb://127.0.0.1:27017/notificator', (err, db) => { if (err) throw err; let collection = db.collection('users'); userExists = collection.find({email: email}).count() > 0; console.log(userExists); db.close(); }); console.log(userExists); return userExists; }
因此, .connect
调用中的第一个console.log
始终返回false
因为.find
的返回值不是数组,它是一个巨大的对象,如下所示:
{ connection: null, server: null, disconnectHandler: { s: { storedOps: [], storeOptions: [Object], topology: [Object] }, length: [Getter] }, bson: {}, ns: 'notificator.users', cmd: { find: 'notificator.users', limit: 0, skip: 0, query: { email: 'email@example.com' }, slaveOk: true, readPreference: { preference: 'primary', tags: undefined, options: undefined } }, options: ........ ........
而最后一个console.log
总是未定义的(尽pipe我认为它不应该是这样,因为await
asynchronous调用的结束,对吧?)
我只需要我的函数返回一个布尔值,而不是一个Promise
或什么的。
有人可以帮我吗?
更新1
console.log(collection.findOne({email: email}));
在.connect
里面返回这个:
{ 'Symbol(record)_3.ugi5lye6fvq5b3xr': { p: [Circular], c: [], a: undefined, s: 0, d: false, v: undefined, h: false, n: false } }
更新2
似乎是我的es7 async/await
知识贫乏的问题。
现在, .connect
的代码返回所需的值。
async userExistsInDB(email) { let userExists; await* MongoClient.connect('mongodb://127.0.0.1:27017/notificator', async(err, db) => { if (err) throw err; let collection = db.collection('users'); userExists = await collection.find({email: email}).limit(1).count() > 0; db.close(); }); console.log(userExists); // <--- this is not called at all return userExists; }
但是,现在console.log
或者.connect
调用之后的任何内容都不会被执行。
现在,每当我调用userExistsInDB()
函数和console.log
的结果,我得到这个:
{ 'Symbol(record)_3.78lmjnx8e3766r': { p: [Circular], c: [], a: undefined, s: 0, d: false, v: undefined, h: false, n: false } }
任何想法,为什么它是这样的?
好吧,我是这样工作的:
async function userExistsInDB(email, password) { let db = await MongoClient.connect('mongodb://127.0.0.1:27017/notificator'); try { let collection = db.collection('users'); let userCount = (await collection.find( { email: email, password: password }).limit(1).count()); return userCount > 0; } finally { db.close(); } }
而且由于函数声明中的async
关键字保证返回的值是一个Promise
,所以得到真正返回结果的唯一方法是:
let result = await this.userExistsInDB(email, password);
里面的另一个函数声明为async
。