簡體   English   中英

從嵌套對象創建MongoDB文檔

[英]Creating MongoDB Document from Nested Object

我敢肯定這是一個簡單的修復程序,但是我一直在努力嘗試使嵌套對象的語法正確。 我正在嘗試使用它來創建MongoDB文檔。

Mongo文檔存儲兩個用戶之間的對話。 對話中的每條消息都存儲在單獨的MongoDB文檔中,並且對話文檔將引用屬於它的每條消息。

這是會話模式(我認為可以)

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

這是我創建對象以傳遞到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. 
            }

這是“參與者”位,真讓我震驚。 這些數據應該從客戶端返回,但是我無法將其放入var conv 在這里創建嵌套對象的正確語法是什么?

任何指導都會很棒! 謝謝大家!

修復! 是的,這只是一個簡單的語法錯誤:這是正確的格式,以防萬一其他人到此為止。

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

另外,提示:走開,洗衣服。 回到您的身邊,事情會變得更加清晰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM