简体   繁体   English

从嵌套对象创建MongoDB文档

[英]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. 我正在尝试使用它来创建MongoDB文档。

The Mongo documents store conversations between two users. Mongo文档存储两个用户之间的对话。 Each message in the conversation is stored in separate MongoDB documents, and the conversation document will reference each message that belongs to it. 对话中的每条消息都存储在单独的MongoDB文档中,并且对话文档将引用属于它的每条消息。

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. 这是我创建对象以传递到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 . 这些数据应该从客户端返回,但是我无法将其放入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. 回到您的身边,事情会变得更加清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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