16

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.

Satvir Sandhu
  • 181
  • 1
  • 1
  • 7

2 Answers2

36

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

Kannan T
  • 1,639
  • 5
  • 18
  • 29
3

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..

iamwtk
  • 1,031
  • 3
  • 13
  • 24