1

I tried to read most of the similar questions(and there are a lot) but couldn't find any solution I could understand.

The document structure as mentioned below-

[
  {RoomID:Room1,
  Boards:[
        {BoardID:Board1,
         Devices:[
         {DeviceID:Dev1}
         ....]
              }
              ....]
                   }
                   .....]

How to add a new Device after querying both RoomID and BoardID?

Harshit
  • 45
  • 2
  • 7

1 Answers1

0

You can get the document with findOne() method. When you have the room object, you can finde the board with this call:

var board = room.Boards.find(board => board.BoardId === BoardID);

Once you have the board you can add it the device:

board.Devices.push(Device);

And finally you have to save the room object in db:

room.save();

Hope it helps

David Vicente
  • 3,091
  • 1
  • 17
  • 27
  • There is only one document. So how do I accomplish board.push? I tried findoneandupdate and elemmatch but that still returns the room object. – Harshit Dec 04 '17 at 12:27
  • I eddited the answer. Check if it helps you – David Vicente Dec 04 '17 at 12:36
  • Thanks a lot for your help. But I am not too comfortable with asynchronous programming as of yet. If I use board directly then it returns an undefined object probably due to nonblocking IO of NodeJS. I tried to use callback but that returns a JSON doc and not the object. Can you please help or suggest a document I could refer to study further. – Harshit Dec 06 '17 at 10:40
  • I don't know exactly where it happens, but probably you can work with the JSON element as an object, or maybe apply board.toObject() and it will work. – David Vicente Dec 11 '17 at 07:59
  • 1
    I was able to do it. Also it helped me clean up the whole API. Thanks a lot. – Harshit Dec 11 '17 at 09:03