I have the below schema (apologies that it is in coffeescript)
Schema = mongoose.Schema
AuthS = new Schema
auth: {type: String, unique: true}
nick: String
time: Date
Auth = mongoose.model 'Auth', AuthS
I simply want to recover one record which is definitely in my database:
Auth.findOne({nick: 'noname'}, function(obj) { console.log(obj); });
Unfortunately this always logs null
. db.auths.findOne({nick: 'noname'})
in mongo shell always returns a value. What is going on?
You might want to consider using
console.log
with the built-in "arguments" object:This will always output all of your arguments, no matter how many arguments you have.
Use obj[0].nick and you will get desired result,
In my case same error is there , I am using Asyanc / Await functions , for this needs to add AWAIT for findOne
above , foundUser always contains Object value in both cases either user found or not because it's returning values before finishing findOne .
above , foundUser returns null if user is not there in collection with provided condition . If user found returns user document.
Found the problem, need to use
function(err,obj)
instead:Mongoose basically wraps mongodb's api to give you a pseudo relational db api so queries are not going to be exactly like mongodb queries. Mongoose findOne query returns a query object, not a document. You can either use a callback as the solution suggests or as of v4+ findOne returns a thenable so you can use .then or await/async to retrieve the document.
See the docs if you would like to use a third party promise library.