提供されたユーザーが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 } }
なぜそうなのか、何か考えはありますか?