使用es7 async / await检查mongodb中是否存在文档

时间:2015-10-31 10:52:06

标签: node.js mongodb node-mongodb-native ecmascript-7

我正在尝试检查集合email中是否存在提供users的用户,但我的函数会为每次调用返回undefined。我使用es6和async/await来摆脱大量的回调。这是我的函数(它在一个类中):

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;
}

因此,console.log调用中的第一个.connect总是返回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总是未定义的(虽然我认为不应该是这样,因为await等待异步调用的结束,对吗?)

我只需要我的函数返回一个布尔值,而不是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 } }

为什么会这样?

1 个答案:

答案 0 :(得分:13)

好的,这是我如何运作的:

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的函数内部。

相关问题