Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use mongoose findOne

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?

like image 634
Callum Rogers Avatar asked Aug 11 '11 21:08

Callum Rogers


People also ask

How does findOne work mongoose?

Mongoose | findOne() Function The findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition.

How do I use findOne update?

As the name implies, findOneAndUpdate() finds the first document that matches a given filter , applies an update , and returns the document. By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.


2 Answers

Found the problem, need to use function(err,obj) instead:

Auth.findOne({nick: 'noname'}, function(err,obj) { console.log(obj); });
like image 139
Callum Rogers Avatar answered Oct 17 '22 23:10

Callum Rogers


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.

// thenables
Auth.findOne({nick: 'noname'}).then(err, result) {console.log(result)};
Auth.findOne({nick: 'noname'}).then(function (doc) {console.log(doc)});

// To use a full fledge promise you will need to use .exec()
var auth = Auth.findOne({nick: 'noname'}).exec();
auth.then(function (doc) {console.log(doc)});

// async/await
async function async auth() {
  const doc = await Auth.findOne({nick: 'noname'}).exec();
  return doc;
}
auth();

See the docs if you would like to use a third party promise library.

like image 14
Isaac Pak Avatar answered Oct 17 '22 23:10

Isaac Pak