I use mongoose. I have the following 2 schemes:

  1. Genre books (Genre)

    { text:{type:String, unique: true} }

  2. Book (Book)

    { title: String, author: String, genres: [{genre:{type:Schema.ObjectId, ref: 'genre'}}] }

When a user adds a book, I need to check whether there are genres, and if not, then insert new ones. So, I do not understand how to do it. Of course, you can do it by 1, but it seems to me that this is not a very good idea. So there was a thought, are there any tools or something similar so that you can solve this problem?

    1 answer 1

    Try $addToSet

     Book.findOne({author: customAuthor}, {$addToSet: {$all: customGenreIdsArray}}) 
    • instead of $ all you need to use $ each - Jackson