简体   繁体   English

如何使用mongoose检查记录/文档是否已存在于MongoDB?

[英]How to check if a record/document already exists in MongoDB using mongoose?

I am trying to check if a record exists in MongoDB using mongoose. For that I am using the function findOne().我正在尝试使用 mongoose 检查 MongoDB 中是否存在记录。为此,我正在使用 function findOne()。 But even if the record/document does not exists the query returns a non null value.但即使记录/文档不存在,查询也会返回一个非 null 值。 How to use this function or any other way to check if a document exists?如何使用这个 function 或任何其他方式来检查文件是否存在? My code is:我的代码是:

var req_username = "";
var req_password = "";
const insertUserIntoDatabase = (requestBody) => {
    req_username = requestBody.username;
    req_password = requestBody.password;
    connectToDatabase();
    if (doesUserExistAlready()==true) {
      console.log("user already there");
    }else{
      insertUser();
    }
}                                              

const connectToDatabase = () => {
  mongoose.connect("mongodb://localhost/my_database",
  {useNewUrlParser:true});
}

const doesUserExistAlready = () => {
  const doc = user.findOne({username:req_username});
  if (doc == null) {
    return false;
  }else{
    return true;
  }
}

const insertUser = () => {
  var newUserDoc = new user();
  newUserDoc.username = req_username;
  newUserDoc.password = req_password;
  newUserDoc.save();
}

This is because mongoose 's findOne returns a "Mongoose document", which is essentially a glorified wrapper.这是因为mongoosefindOne返回一个“Mongoose 文档”,它本质上是一个美化的包装器。 this means if it's a null value it will still have the "mongoose document" properties.这意味着如果它是null值,它仍然具有“猫鼬文档”属性。

You want to be using the lean option to bypass this:您想使用精益选项来绕过这个:

const doc = user.findOne({username:req_username}).lean();

Now if the user does not exist doc will have a null value as expected.现在,如果用户不存在,则doc将按预期具有null值。

Try this:尝试这个:

const connectToDatabase = () => {
    mongoose.connect("mongodb://localhost/my_database", {
        useNewUrlParser: true
    });
}
var req_username = "";
var req_password = "";
user.findOne({
        username: req_username
    })
    .then(async (user) => {
        if (user) {
            console.log("user already there");
        } else {
            var newUserDoc = new user();
            newUserDoc.username = req_username;
            newUserDoc.password = req_password;
            await newUserDoc.save();
        }
    })

Mongoose has a Model.exists() method which returns true if the record exists, or false otherwise. Mongoose 有一个 Model.exists() 方法,如果记录存在则返回 true,否则返回 false。 For instance:例如:

// on your user models file which is inside Models folder
const mongoose = require("mongoose");

let UserSchema = new mongoose.Schema({
  name: { "John Doe", required: [true, "Please provide a name"] }
})
module.exports = mongoose.model('User', UserSchema);

Then in your controllers, import the User from your model like so然后在你的控制器中,像这样从你的 model 导入用户

const User = require('../models/User');

let checkUser = await User.exists({ name: "John Doe" });
console.log(checkUser) // true
// If you check for another name that does not exist, it will return false

Read more here: https://mongoosejs.com/docs/api.html#model_Model-exists在这里阅读更多: https://mongoosejs.com/docs/api.html#model_Model-exists

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

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