我有貓鼬 CastError 問題。我做了一個 nodeJs API。在特定路線上,它回傳附加了一些其他資料的資料。我在這里看到了許多可用的修復程式,但我的情況有所不同。
這是我的模型,問題發生在 fields 屬性上。
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 獲取的 fields 屬性。但它拒絕追加并發生 CastError 。
添加后,它看起來像這樣

嘗試了很多修復后,我無法解決此錯誤。我不知道我錯在哪里。請向我建議一些解決方案。
uj5u.com熱心網友回復:
我可以看到您沒有使用devices變數作為Mongoose Document。devices是一個Documents陣列。
我建議您使用Lean()函式將Document轉換為純 JavaScript 物件,例如
let devices = await Device.find({})
.sort({
timestamp: 'desc',
})
.populate('user_id', ['name'])
.lean();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/354105.html
標籤:javascript 节点.js MongoDB 表达 猫鼬
下一篇:請求一條路線,但我回應另一條路線
