0

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.

2
  • can you please provide console.log(devices ) and console.log(results) for some keys only ? Commented Nov 9, 2021 at 11:40
  • I edited my question and added screenshots of the final data. Commented Nov 9, 2021 at 12:27

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Your solution helps me to solve the problem Thanks for that, but I have a question to clear my concept about it. "devices variable as Mongoose Document". What does that mean Should I get a single document in order to append data in it? I try with a single document without lean() also, but query behavior is same one I was facing before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.