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?
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.
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.
findOneAndUpdate() updates the first matching document in the collection that matches the filter . If no document matches the filter , no document is updated.
The Mongoose Query class provides a chaining interface for finding, updating, and deleting documents.
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) {
});
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