【问题标题】:How to just check if the mongodb .find returns something or not so true or false如何只检查 mongodb .find 是否返回某些东西或不那么真或假
【发布时间】:2022-01-08 21:23:27
【问题描述】:

如何确定.find 是否返回某些内容?我正在努力做到这一点,所以如果它什么都不返回,它会保存一个带有身份验证令牌的模式(检查 2),如果它返回一些东西,它会检查 3。但每次,即使我的 @ 没有模式987654322@ 在它记录check 3check 1 但从不记录check 2 的数据库中。

let discordId = message.author.id;
const discordIdCheck = authSchema.find({
  discordId: discordId,
});
console.log('check 1');
if (discordIdCheck.count() < 1) {
  function getAuthToken() {
    var letters =
      '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!.#&';
    var authTokenStart = '';
    for (var i = 0; i < 12; i++) {
      authTokenStart += letters[Math.floor(Math.random() * letters.length)];
    }
    return authTokenStart;
  }

  const authToken = getAuthToken();

  const auth = {
    discordId: discordId,
    authToken: authToken,
  };
  console.log('check 2');
  message.author.send('Okay, your auth token is: ' + authToken);
  console.log(authToken);
  new authSchema(auth).save();
} else {
  message.channel.send(
    'You already have an auth token. use !token to make me send it to you in your direct messages',
  );
  console.log('Check 3 ');
}

【问题讨论】:

  • 你是不是直接查数据库验证authSchema是空的?
  • 直接检查套件是什么意思? authSchema 等于 require('auth-schema.js') 如果你想要的话
  • @BuzzMoschetti,回复中没有提到你*
  • 你的逻辑看起来不错;第一原则表明discordId 确实存在,这就是为什么您不断收到Check 3
  • findcount 不是 Mongoose 中的两个异步函数吗?

标签: javascript node.js mongodb mongoose discord.js


【解决方案1】:

您可以使用length 值来检查find() 结果的长度,例如:

const discordIdCheck = await authSchema.find({
  discordId: discordId,
});

if(discordIdCheck.length <= 0) console.log("0 found")

【讨论】:

  • 没用,.length 返回 undefined
  • 嗯,我自己试过了,即使没有找到它也会返回0,你能告诉我们authSchema吗?
  • 好吧,我目前不在我的电脑前,但是一旦我回来就编辑帖子并在使用 discordIdCheck.length 时显示变量 authSchema 和 auth-Schema.js 以及我的代码。跨度>
  • 对不起。我在 discordIdCheck 上使用 await 进行了尝试,并将其包装在异步函数中。现在可以了。谢谢!
猜你喜欢
  • 2017-02-12
  • 2013-10-27
  • 2012-06-04
  • 2012-04-29
  • 1970-01-01
  • 2015-02-23
  • 2012-05-11
相关资源
最近更新 更多