Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find by nested property in mongoose

I'm trying to find an object in my database by a nested property, I can't seem to find any way to do it. My schema is below and I have shown how I've attempted to query.

var stations = {
    Alpha: Number,
    Beta: Number
};
var systemSchema = new mongoose.Schema({
    name: String,
    location: String,
    nodes: {
        main: stations,
        secondary: stations,
        tertiary: stations
    }
});

var System = mongoose.model("System", systemSchema);

System.findOne({ nodes: { main: {Alpha: 23000}}}, function(err, system){
    if(err){console.log(err);}
    else{console.log(system);}
});

Every time I run this, nothing gets returned. I was expecting that I would have the corresponding object in my database returned.

like image 502
Satvir Sandhu Avatar asked Feb 18 '19 17:02

Satvir Sandhu


People also ask

How do I find nested objects in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

What is a nested property?

The value of many properties is a reference to another resource. If the value of a property is a reference to a resource, the PropertyRequest might contain a NestedPropertyName object instead of the PropertyName object for the property.

Can I use $in in mongoose?

We can specify as many conditions in the query field. But in cases, where we need to filter according to only one field but more than on values. For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator.

What does find do in mongoose?

The find() function is used to find particular data from the MongoDB database. It takes 3 arguments and they are query (also known as a condition), query projection (used for mentioning which fields to include or exclude from the query), and the last argument is the general query options (like limit, skip, etc).


2 Answers

Change this

System.findOne({ nodes: { main: {Alpha: 23000}}}, function(err, system){
 if(err){console.log(err);}
  else{console.log(system);}
});

to

 System.findOne({ 'nodes.main.Alpha': 23000}, function(err, system){
   if(err){console.log(err);}
   else{console.log(system);}
 });

This will work

like image 114
Kannan T Avatar answered Oct 08 '22 08:10

Kannan T


You can specify the object nesting in form of string.

System.findOne({ "nodes.main.Alpha": 23000 }, function(err, system) {
  if (err) {
    console.log(err);
  } else {
    console.log(system);
  }
});

This should work, can't verify right now but I recall I was using it this way somewhere.

Let me know if it helped..

like image 34
iamwtk Avatar answered Oct 08 '22 10:10

iamwtk