【发布时间】: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