【问题标题】:Mongoose - CastError Cast to string failed for value "Object"Mongoose - CastError Cast to string failed for value "Object"
【发布时间】:2021-11-09 11:19:19
【问题描述】:

我遇到了 Mongoose CastError 问题。我制作了一个 nodeJs API。在特定路由上,它返回附加了一些其他数据的数据。我在这里看到了许多可用的修复程序,但我的情况有所不同。

这是我的模型,问题出现在字段属性上。

 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,
  },
});

我的控制器是

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,
    });
  }
};

它实际上从 InfluxDB 获取数据并将其附加到从 MongoDB 获取的字段属性中,如我的模型中所述。但它拒绝追加并发生 CastError。

添加后是这样的

在尝试了这么多修复后,我无法解决此错误。我不知道我错在哪里。请为此建议我一些解决方案。

【问题讨论】:

  • 能否请您只为某些键提供console.log(devices) 和console.log(results)?
  • 我编辑了我的问题并添加了最终数据的屏幕截图。

标签: javascript node.js mongodb express mongoose


【解决方案1】:

我可以看到您没有使用 devices 变量作为 Mongoose DocumentdevicesDocuments 的数组。

我建议你使用lean() 函数将Document 转换为普通的JavaScript 对象,如

let devices = await Device.find({})
      .sort({
        timestamp: 'desc',
      })
      .populate('user_id', ['name'])
      .lean();

【讨论】:

  • 您的解决方案可以帮助我解决问题 谢谢您,但我有一个问题要澄清我的概念。 “设备变量作为猫鼬文档”。这是什么意思我应该获取一个文档以便在其中附加数据吗?我也尝试使用没有lea() 的单个文档,但查询行为与我之前遇到的相同。
猜你喜欢
  • 2020-10-21
  • 2021-01-07
  • 2017-03-23
  • 2015-08-10
  • 2022-08-23
  • 2017-08-14
  • 2017-02-06
  • 1970-01-01
  • 2019-02-17
相关资源
最近更新 更多