Den*_*nko 12 mongodb node.js 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;
}
Run Code Online (Sandbox Code Playgroud)
所以,调用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:
........
........
Run Code Online (Sandbox Code Playgroud)
并且最后一个console.log总是未定义的(虽然我认为它应该不是那样的,因为await等待异步调用的结束,对吧?)
我只需要我的函数来返回一个布尔值,而不是一个Promise或者什么.
任何人都可以帮助我吗?
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 } }
Run Code Online (Sandbox Code Playgroud)
似乎这是我对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;
}
Run Code Online (Sandbox Code Playgroud)
但是,现在根本不执行通话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 } }
Run Code Online (Sandbox Code Playgroud)
任何想法为什么会这样?
Den*_*nko 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();
}
}
Run Code Online (Sandbox Code Playgroud)
并且因为async函数声明中的关键字保证返回的值是a Promise,所以从这个函数中获取实际返回结果的唯一方法是:
let result = await this.userExistsInDB(email, password);在另一个函数内部声明async.
| 归档时间: |
|
| 查看次数: |
5556 次 |
| 最近记录: |