如何在mongoose中将字符串转换为mongoose.Types.ObjectId

时间:2022-05-31 19:27:26

I just add a field like this in modelSchema

我只是在modelSchema中添加这样的字段

receiverId:[{ type : Schema.Types.ObjectId, ref: 'UserChat' }]

In controller:

在控制器中:

var recievedIds = [];
recievedId = new mongoose.Types.ObjectId(recievedId);
recievedIds.push(recievedId);
console.log(typeof recievedId);
messageInfo.receiverId = recieverIds;
new UserChat(messageInfo).save().then((info)=>{
        res.send(info);
    }).catch((infoError) =>{
        res.send('FAILED_TO_SEND_MESSAGE');
    });

It is giving type as object not as ObjectId and also it is pushing empty array into mongodb i tried removing new infront of mongoose in the above object creation Can anybody help me how to create a ObjectId?

它给类型作为对象而不是ObjectId,并且它将空数组推入mongodb我尝试在上面的对象创建中删除新的mongoose前面可以有人帮我如何创建一个ObjectId吗?

1 个解决方案

#1


0  

As the doc states: An ObjectId must be a single string of 12 bytes or a string of 24 hex characters.

正如doc所述:ObjectId必须是12个字节的单个字符串或24个十六进制字符的字符串。

Please verify that your receiverId meets that requirement.

请确认您的receiverId符合该要求。

#1


0  

As the doc states: An ObjectId must be a single string of 12 bytes or a string of 24 hex characters.

正如doc所述:ObjectId必须是12个字节的单个字符串或24个十六进制字符的字符串。

Please verify that your receiverId meets that requirement.

请确认您的receiverId符合该要求。