【问题标题】:Is this the Correct way of querying in MongoDB using mongoose这是使用 mongoose 在 MongoDB 中查询的正确方法吗
【发布时间】:2021-02-20 16:34:52
【问题描述】:
const {email, username} = req.body
const userExistsbyEmail = User.findOne({
 $and: [{ _id: { $ne: req.params.id } }, { email }],
})
const userExistsbyUsername = User.findOne({
 $and: [{ _id: { $ne: req.params.id } }, { username }],
})

if (userExistsbyEmail || userExistsbyUsername) {
 res.status(400)
 throw new Error('User already exists')
}

我想在更新用户配置文件时获取用户名和电子邮件的详细信息,如果有则显示抛出错误?

谢谢

【问题讨论】:

  • 不知道为什么要按 id 和 2 个单独的查询进行搜索。我会选择User.findOne({ $and: [{ username }, { email }] });

标签: node.js mongodb mongoose


【解决方案1】:

首先,如果您想在存在usernameemail 时抛出错误,我认为最好的方法是在架构中将变量设置为unique

类似这样的:

const model = new moongose.Schema({
  username:{
    type: String,
    unique: true
  },
  email:{
    type: String,
    unique: true
  }
})

然后,当您尝试插入具有相同值的文档时,它会抛出错误:

E11000 重复键错误 dup key: { : "key" }

此外,如果您需要或想要查询,则可以使用以下内容:

db.collection.find({
  "$or": [
    {
      "username": "user"
    },
    {
      "email": "mail"
    }
  ]
})

例如here

如果存在usernameemail这个查询,它将返回文档,然后你可以检查count是否大于0或任何你想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 2012-05-11
    • 2018-12-31
    • 2021-04-29
    • 1970-01-01
    相关资源
    最近更新 更多