skip to Main Content

I am trying to check if a record exists in MongoDB using mongoose. For that I am using the function findOne(). But even if the record/document does not exists the query returns a non null value. How to use this function or any other way to check if a document exists?
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();
}

3

Answers


  1. 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();
            }
        })
    
    Login or Signup to reply.
  2. This is because mongoose‘s findOne returns a "Mongoose document", which is essentially a glorified wrapper. this means if it’s a null value it will still have the "mongoose document" properties.

    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.

    Login or Signup to reply.
  3. Mongoose has a Model.exists() method which returns true if the record exists, or false otherwise. 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

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search