Update specific element in a Mongoose array

Asked

Viewed 417 times

0

How to update the following record:

  "_id": "56dd4489800f800000000000",
  "registro": "2014-09-07T09:06:17.214Z",
  "stars": 0,
  "observacoes": [
    {
      "texto": "",
      "dataResposta": "",
"idUsuario": "56dc9f9f68d7078888888888", "id":2211 }, { "texto": "", "dataResposta": "",
"idUsuario": "56dc9f9f68d707888877778", "id":2212 } ]
How to update an element of the observacoes array using Mongoose? I tested some solutions of the type that follows, but without success.

    Registro.update(
     {_id : req.body._id, "observacoes.id":2212}, 
     { $inc : {stars : 1},
       $set:{texto:"Novo texto", dataResposta: new Date()}}, 
     {multi:false}, 
     function(error, regAfetados){...});
  

1 answer

1


Face actually this remarks should not be an array but another document from Mongo. Something like this:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const _UsersSchema = {
  nome_usuario: String
, telefone_usuario: String
}
const Users = new Schema(_UsersSchema);

const _Schema = {
  nome: {
    type: String
  , required: true
  , index: true
  }
  , id_usuario: Schema.Types.ObjectId
  , usuarios: [Users]
}

You can check the documentation to better understand...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.