skip to Main Content

I am trying to query my database like this

const Admin = require("./model/Admin");

    module.exports = {
    
        validateUser : (uName, pwd) => {
            mongoose.connect("mongodb://127.0.0.1:27017/TeamDK")
            
            //console.log("Uname: " + uName + ", Pwd: " + pwd)
            
            res =  Admin.findOne({ initial: "tt" }).exec()
        }        
    }

In the case above, nothing is returned. The value of res is just null.

I also tried using a call back like this

res =  Admin.findOne({ initial: "tt" }, (err, val) => {
console.log(res)

Using a callback, the output of res is different. I have added a screenshot of this, and only part of it is shown, as it is very big.
enter image description here

I’m sure there is a document in my Model collection. When using monosh like this
TeamDK> db.Admin.findOne({ initial: "tt" }), this is what I get

{
  _id: ObjectId("63ebbd6c59097f4a25f23d31"),
  firstName: 'Test',
  initial: 'tt',
  lastName: 'Unknown',
  email: '[email protected]',
  password: '123',
  role: 4
}

If it’s of any use, my model looks like this:

const adminSchema = mongoose.Schema({
    firstName : { 
        type : String,    
        required : [true, "Why no name?"]
    },
    initial: {
        type: String,
        required: [true, "Why no initials?"],
        index: {unique: true }
    },
    lastName : {
        type : String,
        required : [true, "Why no last name?"]
    },
    email : {
        type : String,
        required : [true, "Then how are we gonna contact you?"],
        index: {unique: true }
    },
    password : {
        type : String,
        required : [true, "Come one man"]
    },
    dateCreate : { 
        type : Date, 
        default : Date.now 
    }, 
    role : {
        type : mongoose.Types.ObjectId,
        ref : "role"
    }     
})

module.exports = mongoose.model("Admin", adminSchema);

I’ve spent almost a day trying to fix this, tried following guids on https://mongoosejs.com/ and tried looking for similar problems here on stackoverflow, but I just can’t figure out what I’m doing wrong

————————- Update —————————

I have also tried making the function async, and use await. I tried isolating the code in a new file and doing like this

const mongoose = require ("mongoose");
const Admin = require("./model/Admin");

async function testAdmin() {
    await mongoose.connect("mongodb://127.0.0.1:27017/TeamDK")            
    
    res = await Admin.findOne({ initial: "tt" }).exec()

    console.log(res)
}

testAdmin()

I also tried removing the exec(), doing

res = await Admin.findOne({ initial: "tt" })

I’m still getting null returned. Any other suggestions are most welcome

————————- Update —————————

I have just noticed that if I do: res = await Admin.find() it works. Though it finds all the documents, and I only need a specific one, but it shows that it does contact the database. For some reason, it does not seem to accept the res = await Admin.findOne(...)

2

Answers


  1. Chosen as BEST ANSWER

    I finally found out what the issue is. For some reason, it's as if the document that I was querying doesn't exist when I try to find it through node.js. I can find it when using mongosh though. I tried to query another document in the collection, and that one it found. So I tried yet another one, and that one it also finds. It seems to find all other, except this one (no matter which field I use as argument, it just returns null):

    {
      _id: ObjectId("63ebbd6c59097f4a25f23d31"),
      firstName: 'Test',
      initial: 'tt',
      lastName: 'Unknown',
      email: '[email protected]',
      password: '123',
      role: 4
    }
    

    Yet I created it exactly the same way as all the others. I have no idea why I can't query this in nodejs, and it's a problem if it should ever act like that in an application. Thankfully this is just practice. It's very likely that they error is at my side, but I haven't located it.

    So should anyone experience the issue of not being able to access a document that you're certain is there (using nodejs), try see if you can access another document in the collection


  2. The .findOne is asynchronous, we must use await or callback to receive its result:

    const Admin = require("./model/Admin");
    
    module.exports = {
        validateUser : async (uName, pwd) => {
            await mongoose.connect("mongodb://127.0.0.1:27017/TeamDK") // It's better to put this connect function somewhere else, not in the Model
                
            res = await Admin.findOne({ initial: "tt" });
            return res;
        }        
    }
    

    Then use it a controller like this, example in Express

    // The connect function is better here
    // mongoose.connect("mongodb://127.0.0.1:27017/TeamDK") 
    
    app.post('/', async (req, res) => {
        const result = await validateUser('username', 'password');
        res.json(result);
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search