[英]How to insert ref objectId in nodejs?
{ name: { type: String, trim: true, required: true }, carModels: [{ type: ObjectId, ref: 'CarModel' }] }
{ name: { type: String, trim: true, required: true }, carModels: [ { type: ObjectId, ref: 'CarModel' } ] },
{ name: { type: String, trim: true, required: true } },
Here i am trying to insert the data like this在这里我试图插入这样的数据
{ "name": "test", "phoneNumber": "0123456789", "email": "m@m.com", "carMakes": [{ "name": "BMW", "carModels": [{ "_id": "some id" }] }] }
and it giving me error like它给了我这样的错误
carMakes.0: Cast to [ObjectId] failed for value
here is the create function这里是创建 function
export const create = async data => {
const result = await Booking(data).save();
return result;
};
Can anyone tell what I am missing here..i am learning nodejs谁能告诉我在这里缺少什么..我正在学习nodejs
i think the problem is with the _id
that you're passing to carModel
and since you set the type to ObjectId
it has to be in a valid format "either 12 byte binary string, or a 24 hex byte string" and "some id" is not the valid one if you're sending that.我认为问题出在您传递给carModel
的_id
上,并且由于您将类型设置为ObjectId
,因此它必须采用有效格式“12 字节二进制字符串或 24 十六进制字节字符串”和“某些 id”如果您要发送它,则不是有效的。
you can check if your id is valid with isValidObjectId() function.您可以使用isValidObjectId() function 检查您的 id 是否有效。
or you can easily generate an ObjectId
:或者您可以轻松生成ObjectId
:
var mongoose = require('mongoose');
var id = new mongoose.Types.ObjectId();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.