My workflow goes like this i fetch data from my login schema like this
const userSchema = new mongoose.Schema({
username: String,
password: String,
department: { type: Schema.Types.ObjectId, ref: ‘departments’ },
// other fields…
});
const Login = mongoose.model(‘Login’, userSchema);
const employeeSchema = new mongoose.Schema({
login_id: { type: mongoose.Schema.Types.ObjectId, ref: ‘Login’ },
employeeCode: String,
firstName: String,
// other fields…
});
const BasicEmployee = mongoose.model(‘basic-employee’, employeeSchema);
const fetchData = await Login.find({ department: department_id });
const loginIds = fetchData.map(item => item._id);
console.log('loginIds:', loginIds, loginIds.every(id => id instanceof mongoose.Types.ObjectId));
and then it returns data like this
loginIds: [
new ObjectId(‘67fcaee2d7d3b3e80fa8d45b’),
new ObjectId(‘67fcaee4d7d3b3e80fa8d51b’),
new ObjectId(‘67fcaee6d7d3b3e80fa8d59b’),
new ObjectId(‘67fcaeead7d3b3e80fa8d6db’),
new ObjectId(‘67fcaeefd7d3b3e80fa8d8ab’),
new ObjectId(‘67fcaeefd7d3b3e80fa8d8bb’)
] true
now when i try to find from the basic employee schema usign login ids
const employees = await BasicEmployee.find({
login_id: { $in: loginIds }
});
it returns error like this
CastError: Cast to ObjectId failed for value “{
‘$in’: [
new ObjectId(‘67fcaee2d7d3b3e80fa8d45b’),
…
]
}” (type Object) at path “login_id”
upon further debugging i found that login id should be a valid object id in basicemployee schema
i furthter check these things
All _ids in loginIds are valid ObjectIds.
login_id field in basic-employee schema is of type ObjectId and correctly references Login.
No stringified JSON, all ObjectIds are real and direct.
Logging typeof loginIds[0] gives “object” and instanceof mongoose.Types.ObjectId is true.
Am I missing something obvious? Is there a deeper reason this $in is being casted as a string object?