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?
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.
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.
Found the problem, need to use function(err,obj)
instead:
Auth.findOne({nick: 'noname'}, function(err,obj) { console.log(obj); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With