Search code examples
node.jsmongodbnode-mongodb-nativerestify

find object inside JSON using nested ID


i have a mongo collection like this

{"stores": [{"name": "foo",
             "songs": [ {"id": "", "name": "", "artist": "", "category": "", "tags": []} ],
             "songsSchedule": [
                               {
                                "song_id": "",
                                "date": ,
                                "user": "",
                                "help": ,
                                "partners": [{"user": ""}],
                                "likes":
                               }
                             ]
 }]}

and i want to get the songs name and artist from the songsSchedule song_id, i've tried this but it's not working

var query = { _id: fn.generateID(req.params.store_id), songsSchedule: { $exists: true } };
var select = { songsSchedule:1 };
var array = [];

client("stores", function(err, collection) {
    if (err) 
       return res.json(fn.status("30"));

  collection.findOne(query, select, function(err, store) {
        if (err || !store) 
           return res.json(fn.status("31"));

    for (var i in store.songsSchedule) {
      var song = store.songsSchedule[i];
      array.push(song.song_id);
    }

    collection.find({ _id: fn.generateID(req.params.store_id), "songs._id": { $in: array } }, function(err, songs) {

      res.json(songs);
    });
    });
});

and i dont really know if it's the best way of doing it


Solution

  • I'm not entirely clear what you mean by "get the songs name and artist from the songsSchedule song_id" but it looks like that query will be messy.

    If it were me, I'd consider splitting out songs and songSchedule into their own collections for easier querying.