Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

534
Vistas
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(). 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();
}
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Santiago Trujillo Denunciar

0

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();
        }
    })
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda