【问题标题】:mongodb: How to create _id for each array element?mongodb:如何为每个数组元素创建_id?
【发布时间】:2016-05-06 00:09:54
【问题描述】:

有没有一种方法,每当我在 monodb 数组中 $push 一个新元素时,都会向其中添加一个普通的 _id?我记得 mongoose 会自动执行类似的操作,但现在我使用的是 mongodb 的原生 js,它似乎没有插入任何 _id。

例子:

chats.updateOne({_id: chat_id},
            {$push: {messages: 
                    {
                        message: data.message,
                        date: new Date(),
                    }}},
            function(err, response){}
)};

在执行时,messages 数组应该有常规的 _id 字段、message 和 date。目前它只创建消息和日期。

【问题讨论】:

  • 您需要为messages创建架构

标签: javascript node.js mongodb


【解决方案1】:

你可以使用ObjectId():

chats.updateOne({_id: chat_id},
            {$push: {messages: 
                    {
                        message: data.message,
                        date: new Date(),
                        _id: ObjectId()
                    }}},
            function(err, response){}
)};

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多