Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
mongoose schema findone and update array subdocument

This is my mongoose schema:

userId is a unique number generated by Okta for user profiles. '''

var book_listSchema = new mongoose.Schema({

userId:{type: String, required: true},
first_name: { type: String, required: true},
last_name:{ type: String, required: true},
newList: [{

         list_name: String,
         books:
    [{
        book_name: {type: String, required: true},
        book_author: {type: String, required: true},
        date_added: {type: Date, default: Date.now},
        date_finished: {type: Date, default: Date.now},

    }]}],


    });

'''
   

This is the code I'm using to find and update, adding a book to the books array.

 '''
 book_list.findOneAndUpdate({"userId": req.userContext.userinfo.sub, newList:{"newList.list_name": list_name}}, {$push:{books:{book_name: title, book_author:author, date_added: new Date()}}}

 '''

The books array does not get updated and each object in newList has the list_name, and there are different lists each with their own books array, so the correct list needs to be updated when a book is added.

Sample data set:

  '''
            _id:625c81d7622b044fb297ce54

             userId:"00uvgyn7OikAwud6"
             first_name:"John"
             last_name:"Smith"
             newList:Array
                 0:Object
                   list_name:"read"
                   books:Array
                      0:Object
                      book_name:"The Great Gatsby"
                      book_author:"Francis Scott Fitzgerald"
                      date_added:2022-04-19T00:43:24.248+00:00
                     _id:625e05ac083663dc44f37804
                    date_finished:2022-04-19T00:43:24.252+00:00
                    _id:625e05ac083663dc44f37803
                    __v:0
  '''
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The right way is:

db.collection.update({
  userId: "00uvgyn7OikAwud6",
  newList: {
    $elemMatch: {
      list_name: "read"
    }
  }
},
{
  $push: {
    "newList.$.books": {
      book_name: "a new book",
      book_author: "some author",
      date_added: new Date()
    }
  }
})

or in your code way

db.collection.update({
  userId: req.userContext.userinfo.sub,
  newList: {
    $elemMatch: {
      list_name: list_name
    }
  }
},
{
  $push: {
    "newList.$.books": {
      book_name: title,
      book_author: author,
      date_added: new Date()
    }
  }
})

$elemMatch allows you to match more than one component within the same array element and then you can use $push to add the specific object in the array.

You can run it here to check the same query https://mongoplayground.net/p/YnzDRfhwpEt

You can also have a look at documentation of $elemMatch in this link.

Let me know if you face any issue.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda