Creating MongoDB Document from Nested Object
<p>I'm sure it's a simple fix, but I've been pulling my hair out trying to get the syntax correct for a nested object. I'm trying to use it to create a MongoDB document. </p>

<p>The Mongo documents store conversations between two users. Each message in the conversation is stored in separate MongoDB documents, and the conversation document will reference each message that belongs to it.</p>

<p>Here's the Conversation Schema (which I think is OK)</p>

<pre><code>var ConversationSchema = new mongoose.Schema({
  participants: [
    {
      user1: {
        id: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "User"
            },
        username: String
      },
      user2: {
        id: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "User"
            },
        username: String
      },
    },
  ],
  started: Number,
  messages: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Message"
    }
  ]
});
</code></pre>

<p>And here's one of my many attempts at creating the object to pass into MongoDB. </p>

<pre><code>var conv = {
              participants : {
                "participants.user1.id" : req.body.senderId,
                "participants.user1.username" : req.body.senderName,
                "participants.user2.id" : req.body.recipientId,
                "participants.user2.username" : req.body.recipientName
              },
              created : Date.now(),
              messages : [] // The message _id is pushed in later. 
            }
</code></pre>

<p>It's the 'participants' bit which is really tripping me up. This data is coming back from the client as it should, but I can't manage to get it into my <code>var conv</code>. What's the correct syntax to create the nested object I need here?</p>

<p>Any guidance would be awesome! Thanks peoples!!</p>