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

603
Visualizações
Mongoose - CastError Cast to string failed for value "Object"

I have Mongoose CastError issue. I made a nodeJs API. At the specific route, it returns data appended with some other data. I saw many fixes available here but my scenario is different.

Here is my model and the problem occurs at fields property.

 const deviceSchema = new Schema({
  device_id: { type: String, required: true },
  user_id: { type: Schema.Types.ObjectId, ref: 'User', require: true },
  location_latitude: { type: String, default: '0' },
  location_longitude: { type: String, default: '0' },
  fields: [{ type: String }],
  field_id: { type: Schema.Types.ObjectId, ref: 'Field', required: true },
  timestamp: {
    type: Date,
    default: Date.now,
  },
});

and my controller is

exports.getAllDevices = async (req, res) => {
  try {
    let devices = await Device.find({})
      .sort({
        timestamp: 'desc',
      })
      .populate('user_id', ['name']);

    // Let us get the last value of each field
    for (let i = 0; i < devices.length; i++) {
      for (let j = 0; j < devices[i].fields.length; j++) {
        if (devices[i].fields[j] !== null && devices[i].fields[j] !== '') {
          await influx
            .query(
              `select last(${devices[i].fields[j]}), ${devices[i].fields[j]} from mqtt_consumer where topic = '${devices[i].device_id}'`
            )
            .then((results) => {
             ************** Problem occurs here ************** 
              if (results.length > 0) {
                devices[i].fields[j] = {
                  name: devices[i].fields[j],
                  last: results[0].last,
                };
              } else {
                devices[i].fields[j] = {
                  name: devices[i].fields[j],
                  last: 0,
                };
              }
            ************** Problem occurs here **************  
            });
        }
      }
    }

    // Return the results
    res.status(200).json({
      status: 'Success',
      length: devices.length,
      data: devices,
    });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      error: err,
    });
  }
};

It actually gets data from InfluxDB and appends it to fields property which was fetched from MongoDB as mentioned in my model. But it refused to append and CastError occurs.

After addition, it will look like this

enter image description here

I can't resolve this error after trying so many fixes. I don't know where I'm wrong. Please suggest to me some solution for this.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I can see you are not using devices variable as Mongoose Document. devices is an array of Documents.

I would like to suggest you to use lean() function to convert from Document to plain JavaScript object like

let devices = await Device.find({})
      .sort({
        timestamp: 'desc',
      })
      .populate('user_id', ['name'])
      .lean();
about 4 years ago · Juan Pablo Isaza 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