简体   繁体   中英

Creating MongoDB Document from Nested Object

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.

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.

Here's the Conversation Schema (which I think is OK)

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"
    }
  ]
});

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

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

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 var conv . What's the correct syntax to create the nested object I need here?

Any guidance would be awesome! Thanks peoples!!

Fixed it! Yep it was just a simple syntax error: here's correct form in case anyone else ends up here.

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

Also, pro tip: Go away and do the washing up. Things will be much clearer when you come back to them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM