[英]mongodb: How to create _id for each array element?
Is there a way that whenever I $push a new element in monodb array, a normal _id is added to it? 有没有一种方法,每当我$$ monodb数组中的一个新元素时,添加一个普通的_id? I remember that mongoose was doing something like that automatically but now I am using mongodb's native js and it seems to be not inserting any _id.
我记得猫鼬会自动执行类似的操作,但是现在我正在使用mongodb的本机js,而且似乎没有插入任何_id。
Example: 例:
chats.updateOne({_id: chat_id},
{$push: {messages:
{
message: data.message,
date: new Date(),
}}},
function(err, response){}
)};
On executing, messages array should have regular _id field, message and date. 执行时,messages数组应具有常规的_id字段,消息和日期。 Currently it only creates message and date.
当前,它仅创建消息和日期。
You can use ObjectId() : 您可以使用ObjectId() :
chats.updateOne({_id: chat_id},
{$push: {messages:
{
message: data.message,
date: new Date(),
_id: ObjectId()
}}},
function(err, response){}
)};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.