I'm running a simple application with mongoDB + nodejs, I'm trying to achieve the following:
The unit belongs to a company, the classroom belongs to a unit and the user belongs to a classroom.
In certain moment, I want to add the user to another unit or/and classroom, then he'll belong to 2 or more units/classrooms.
My form will sent only one unit/classroom per time, in this case, I want to add it to the user model unit:[string] and classroom:[string] only if he doesn't previously belong to it. So I need to check if the arrays already have the sent data, if don't, add to it.
Mongo has the $addToSet property, and the $ne to do it, but I can't seem to make it work.
Here's my code:
User.findById(req.body._id)
.select("-__v")
.exec((err: Error, user: any) => {
if (err) {
// display error
}
if (!user) {
// display error
}
user.update({
unit: {
$ne: user.unit
},
classroom: {
$ne: user.classroom
}
}, {
$addToSet: {
unit: req.body.unit,
classroom: req.body.classroom
}
}).exec((err: Error) => {
if (err) {
// Display error
}
res.status(200).json({
status: "OK",
response: response,
})
return
})
It belongs to "Academy one" and the classroom id reference, I will add him to another unit like "Academy 2" and add another classroom reference, but if I add him to another classroom of "Academy One", I don't want a duplicate item in it's unit array.
When I post the following through postman, it gives me the error:
{
"_id":"5d8ba151248ecb4df8803657", // user id
"unit":"Test", // another unit
"classroom":"5d8a709f44f55e4a785e2c50" // another classroom
}
Response:
{ "status": "NOK", "response": "Cast to [string] failed for value \"[{\"$ne\":[\"Academy One\"]}]\" at path \"unit\"" }
What am I missing?

"Cast to [string] failed for value \"[{\"$ne\":[\"Academy One\"]}]\" at path \"unit\""user.Update(..).exec((error:Error) => if (err){//cast error here}block$addToSetworks for array field?