Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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?

2 Answers

0 votes
by (106k points)

To use mongoose findOne you need to use function(err,obj) instead:

Auth.findOne({nick: 'noname'}, function(err,obj) { console.log(obj); });

0 votes
by (107k points)

Mongoose findOne query only 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.

Related questions

0 votes
2 answers
0 votes
1 answer
+1 vote
2 answers
0 votes
2 answers
asked Oct 17, 2019 in Web Technology by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...