Home > Net >  Mongoose - CastError Cast to string failed for value "Object"
Mongoose - CastError Cast to string failed for value "Object"

Time:11-10

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.

CodePudding user response:

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();
  • Related