Mongoose cannot populate with String as _id - string

I created a database on MongoDB setting the _id (string) of the documents myself. Now when I try to find and populate I get this error:
error :>> CastError: Cast to ObjectId failed for value "jaguar_warrior" (type string) at path "_id" for model "Unit"
messageFormat: undefined,
stringValue: '"jaguar_warrior"',
kind: 'ObjectId',
value: 'jaguar_warrior',
path: '_id',
reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
valueType: 'string'
The part of the model I'm trying to populate is this:
unique_unit: [{
type: String,
ref: 'Unit'
}],
On the mongoDB it doesn't allow me to make the _id from string to objectId.
I read online that _id can be string but it seems not to work.
Thanks

Try thisto convert string to ObjectId
unique_unit: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Unit'
}],

Related

after nodejs update i get this error: Cast to ObjectId failed for value "600204c674086624b9de76e2" at path "classId" for model "Message"

this is my code:
async function allMessage(roomId){
await Message.find({ classId: roomId }).sort({ date: -1 }).limit(4)
.populate('userId', 'name')// just select name
.exec(function(allMessage){
console.log(allMessage);
})
}
and this is my model structure:
userId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
classId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'Classroom'
},
message:{
type: String,
required: true
},
date:{
type: Date,
default: Date.now
}
but i get this error: Cast to ObjectId failed for value "600204c674086624b9de76e2" at path "classId" for model "Message"
I try to change roomId to ObjectId with this code:
mongoose.Types.ObjectId(roomId)
but i get this error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
befor updating the nodejs it works fine. I confused now. what should I do?
try using trim() on the string id you are getting and then pass it in the query

Cast Errors While Populating Referenced Mongoose Documents

My schema looks like the following:
User Schema {
name: String,
email: String
}
Job Schema {
title: String,
owner: { type: Schema.Types.ObjectId, ref: 'User' },
helper: { type: Schema.Types.ObjectId, ref: 'User' }
}
Both Users and Jobs use ObjectId's as their ID type.
Part of my application requires me to query the job collection for jobs that fit certain criteria. As part of this query I perform a population of the referenced user documents. Somethings like the following:
Job
.find(query, null, options)
.populate('owner helper', 'name email')
.sort(sort)
.exec(err, function(results) {
...Do Something with populated documents
})
However, this is throwing an error.
{ message: 'Cast to ObjectId failed for value "b" at path "_id"',
name: 'CastError',
type: 'ObjectId',
value: 'b',
path: '_id' }
I have checked all of the user object's ids and they all seem valid. I don't understand what could be causing this error.
Any help would be appreciated.

mongoose self reference with own ObjectId throwing: cast to ObjectId failed

I am using nodejs, mongoose and I trying to build a shema that contains a reference to itself via parent. Parent should be a reference to DataType.
var DataTypeSchema = new Schema({
_id: String,
label: { type: String, required: true },
comment: { type: String },
url: { type: String, required: true },
parent: { type: Schema.Types.ObjectId, ref: 'DataType' },
values: []
});
var DataType = mongoose.model('DataType', DataTypeSchema);
module.exports.DataType = DataType;
Every DataType has own ID(not generated by mongo) and I think this is a place where it causes problems. It throws me an error cast to objectid failed for value "Number" at path "parent", where Number is object with ID "Number" already saved in DB.
Thanks
The type of the parent reference must match the type of the _id in the model it references. So instead of Schema.Types.ObjectId it should be String:
...
parent: { type: String, ref: 'DataType' },
You can try this
parent: [ this ]
It works

How do I define a key named "type" in Mongoose?

I have a Schema definition with a nested object that looks like this:
mongoose.Schema({
name: String,
messages: [{
type: String,
message: String
}]
});
Mongoose doesn't interpret this as I would like because there is a key named type, which conflicts with Mongoose's syntax for defining defaults, etc. Is there a way to define a key named "type"?
Oh, I remember this annoying problem, it took me ages to find out that the problem is that type is read by mongoose schema.
Just specify a type:String inside the type label
mongoose.Schema({
name: String,
messages: [{
type: {type: String},
message: String
}]
});

MongoDB cast error in _id

I am using mongoose.
My schema is like
var tblTypes = new Schema({
_id: { type: String, required: true }
, desc: String
, priority: Number
}, { collection: 'tblTypes' });
while fetching records in the query i am giving like dis as query in findone
JSON
{ _id: "SFK" }
Its giving
{ message: 'Cast to ObjectId failed for value "CONFIRM" at path "_id"',
name: 'CastError',
type: 'ObjectId',
value: 'CONFIRM',
path: '_id' }
as error. Earlier its working in different system.
I am not sure about both the versions.
Where i am going wrong ?

Resources