I have a scenario object that I want to save using Mongoose. The scenario object has a "user" field, which should be an ObjectId referencing a "User" document. Here’s the schema definition:
const Scenario = new Schema({
user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
name: { type: String, required: true },
categories: [{ type: Schema.Types.ObjectId, ref: 'Category' }],
questions: [{ type: Schema.Types.ObjectId, ref: 'Question' }],
createdAt: { type: Number, default: Date.now, required: true },
updatedAt: { type: Number, default: Date.now, required: true }
});
I’m passing the scenario data to Mongoose as follows:
const scenario = new Scenario({
user: "user_id_here",
name: "scenario1",
categories: ["648da0a443d3568c50c873e7"]
});
await scenario.save();
However, when I check the saved scenario in the database, the user
field is not set to the provided user_id_here
value. Instead, it has a different value like 757365725f69645f68657265
. Why does this happen? (Noted that, neither user_id_here
nor 757365725f69645f68657265
is an id in User table)
Also, if I change the user
value to user_id_here1
, I get a validation error: Cast to ObjectId failed for value 'user_id_here1' (type string) at path 'user' because of 'BSONTypeError'.
What could be causing this error?
2
Answers
You don’t get an error by chance when the user value is
user_id_here
because it is 12 character length.But when you use value
user_id_here1
, since it is 13 characters length you get validation error.You can validate the user value using isObjectIdOrHexString function before trying to save.
You are getting the error because you are passing the string.
Solution :
You have to parse the string into ObjectId using below code