简体   繁体   中英

add item to array if it doesn't exist mongodb

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?

Actually, I didn't needed the $ne operator, I just needed to use the $addToSet directly

user.updateOne({
  $addToSet: { unit: req.body.unit, classroom: req.body.classroom }
}).exec((err: Error) => {

Thanks!

You need to use $nin instead of $ne , https://docs.mongodb.com/manual/reference/operator/query/nin/

unit: {$nin: [user.unit]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM