【问题标题】:MongoDB User.findOne({email:email})MongoDB User.findOne({email:email})
【发布时间】:2021-07-14 17:35:27
【问题描述】:

findOne 总是返回 null

我在数据库中有“user(hello@gmail.com)”数据,但 User.findOne 总是返回 null。请帮我。我有一个在后台运行的节点,但它给了我 null 。 req.body 给出了我通过但 findOne 不工作的电子邮件。 User.create 工作正常。但是像 find,findById,findOne 这样的搜索查询不起作用。有人请帮助我。

const userSchema = new mongoose.Schema({
 name: {
    type: String,
    required: [true, 'A user must have a unique name'],
    unique: true,
  },
  password: {
    type: String,
    required: true,
    unique: true,
    minlength: 8,
  },
  email: {
    type: String,
    required: [true, 'A user must have a unique name'],
    unique: true,
    lowercase: true,
  }
const User = mongoose.model("User", userSchema);

exports.getTest=async (req,res)=>{
    const {email} = req.body  // returns "hello@gmail.com"
    const user = await User.findOne({email})
    console.log(user) //returns null
    res.json({
     
        status:"success",
        data:{
            user
        }
    })

}

【问题讨论】:

  • 您的电子邮件字段中可能有空格或不匹配。你的语法看起来是正确的,你不需要 exec()。三重检查所有假设,因为这些是万恶之源。
  • 有人告诉我 .exec() 使 Mongoose 请求异步,我永远无法检查这是不是真的
  • 这是我第二周试图找到我的错误。我找不到。这就是为什么我需要你们的帮助

标签: javascript jquery node.js mongodb mongoose


【解决方案1】:

我感觉你的问题在于测试的前两行?

const {email} = req.body  // returns "hello@gmail.com"
const user = await User.findOne({email})

如果您的req.body 只返回电子邮件字符串,那么您的查询可能不是正确的 JSON 格式?

您确定查询实际上最终是 User.findOne({email: "hello@gmail.com"}) 而不仅仅是 User.findOne("hello@gmail.com")

也不确定最后是否需要exec()but it does execute the query and return a Promise...

【讨论】:

  • User.findOne({email: "hello@gmail.com"}) 是的先生。我检查了百万次。查询不起作用,我不知道为什么
【解决方案2】:

文档应在数据库中保存active: true。但相反,我将每个文档都保存为 false 作为默认值。因此,如果将来有人觉得它有用,请告诉我,这就是我的答案。保重,再见

【讨论】:

    猜你喜欢
    • 2020-08-10
    • 2021-06-02
    • 1970-01-01
    • 2019-04-06
    • 2023-03-19
    • 1970-01-01
    • 2020-07-24
    • 2019-12-20
    • 2019-07-12
    相关资源
    最近更新 更多