Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose findOne on object property

I have a mongoose schema as follows

var user_schema = new Schema({
    reset : { type: Schema.Types.Mixed, required: true }
});

where reset is being given an object like this to store in the database

{
    id: 23,
    name: 'something'
}

I would like to look up a document based on the id in the reset object. This is what I have tried but I never get a result returned.

models.Users.findOne({ 'reset.id': id }, function (err, user) {
    // user is null 
});

Is a lookup like this possible with mongoose?

like image 221
Errol Fitzgerald Avatar asked Nov 13 '12 15:11

Errol Fitzgerald


People also ask

What does findOne return mongoose?

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.

How does a mongoose findOne work?

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 does findOneAndUpdate works?

findOneAndUpdate() updates the first matching document in the collection that matches the filter . If no document matches the filter , no document is updated.

What is query in mongoose?

The Mongoose Query class provides a chaining interface for finding, updating, and deleting documents.


1 Answers

I think the issue you're having is with using mixed schema type.

Could you not use an embedded doc of Reset

var reset_schema = new Schema({
    id        : Int,
    name      : String
});

var user_schema = new Schema({
    name      : String,
    reset     : reset_schema 
});

And then querying like:

models.Users.findOne({ 'reset.id': id }, function (err, user) {

});
like image 120
Alex Avatar answered Sep 28 '22 02:09

Alex