简体   繁体   中英

How to check if item exists in MonoDB array?

I have a MongoDB model:

const userSchema = new Schema = ({
name: { type: String },
company: [
    companyId: {
        type: String,
      },
      movies: [
      {
          genre: {
              type: String,
              enum: [
              'horror',
              'comedy',
              'action',
              'romance',
              ],
          },
          ratings: { type: String }
        },
      ]
    ],
})

In my query, I have an endpoint that pushes a genre to the movies array but I want to check if there is an existing genre with the name already, if it exists, I want to show a message that says it already exists, otherwise, push the new items to the movies array

    const result = await UserProfile.updateOne(
      {
        _id: id,
        'company.companyId{ $eq: req.params.companyId},
    'company.movies.$.genre': {
      $eq: { genre: req.body.genre},
    },
   }
      },
      {
        $push: {
          'company.$.movies': {
            ...model,
          },
        },
      },
      { new: true, runValidators: true }
    ).catch((err) => handleErrorThrow(err));

    if (result.nModified === 0)
      throw new CustomError(409, 'Movie exists already');

And if I want to remove the array based on another endpoint, I tried the same thing it doesn't work

const result = await UserProfile.updateOne(
    {
        _id: id
        }
    },
    {
        $pull: {
            company: {
            $elemMatch: {
                companyId: req.params.companyId,
                "movies.genre": {
                    $ne: req.body.genre
                }
            }
        }
    },
    { new: true, runValidators: true }
)
.catch((err) => handleErrorThrow(err));

if (result.nModified === 0)
      throw new CustomError(409, 'Not exist');

It returned Not exist'

use $elemMatch for nested array condition, and $ne for genre should not exists before push into movies ,

const result = await UserProfile.updateOne(
    {
        _id: id,
        company: {
            $elemMatch: {
                companyId: req.params.companyId,
                "movies.genre": {
                    $ne: req.body.genre
                }
            }
        }
    },
    {
        $push: {
            "company.$.movies": model
        }
    },
    { runValidators: true }
)
.catch((err) => handleErrorThrow(err));

if (result.nModified === 0) {
    throw new CustomError(409, 'Movie exists already');
}

And if I want to remove the array based on another endpoint

const result = await UserProfile.updateOne(
    {
        _id: id,
        company: {
            $elemMatch: {
                companyId: req.params.companyId,
                "movies.genre": req.body.genre
            }
        }
    },
    {
        $pull: {
            "company.$.movies": {
                genre: req.body.genre
            }
        }
    },
    { runValidators: true }
).catch((err) => handleErrorThrow(err));

if (result.nModified === 0) {
    throw new CustomError(409, 'Not exist');
}

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