简体   繁体   English

这是使用 mongoose 在 MongoDB 中查询的正确方法吗

[英]Is this the Correct way of querying in MongoDB using mongoose

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')
}

I want to get the details of username and email during updating the userprofile , if there is then it show throw an error?我想在更新用户配置文件期间获取用户名和电子邮件的详细信息,如果有则显示抛出错误?

Thank you谢谢

First of all, if you want to thrown an error when username or email exists I think the best way is set your variables as unique in you schema.首先,如果您想在usernameemail存在时抛出错误,我认为最好的方法是将变量设置为架构中的unique变量。

Something like this:像这样的东西:

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

Then, when you try to insert a document with the same value it will thrown an error:然后,当您尝试插入具有相同值的文档时,它会引发错误:

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

Also, if you need or you want a query then you can use something like this:此外,如果您需要或想要查询,则可以使用以下内容:

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

Example here .示例在这里

With this query if exists the username or email it will return the document, and then you can check if count is greater than 0 or whatever you want.通过此查询,如果存在usernameemail ,它将返回文档,然后您可以检查count是否大于 0 或任何您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM