Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

601
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!