我试图通过id一次更新多个记录。我得到下面的错误。我已经确保/weather/:id低于/weather/updateMultiple。我无法解决这个问题(ChatGPT也不能)。请帮助。
对于模型“Weather”的路径“_id”处的值“updateMultiple”(类型字符串),转换为ObjectId失败
产品代码:
//update multiple data in 'weather' collection (PUT http://localhost:3000/weather/updateMultiple)
app.put('/weather/updateMultiple', async (req, res) => {
try {
const updates = req.body;
// Array to store updated documents
const updatedWeatherArray = [];
// Iterate over each update object in the request body
for (const update of updates) {
const { _id, ...fieldsToUpdate } = update;
// Find and update the document
const updatedWeather = await Weather.findByIdAndUpdate(_id, fieldsToUpdate, { new: true });
// Cannot find record in DB
if (!updatedWeather) {
return res.status(404).json({ message: `Cannot find field with ID ${_id}` });
}
// Add the updated document to the array
updatedWeatherArray.push(updatedWeather);
}
// Found records and updated
res.status(200).json(updatedWeatherArray);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
});
//update data in 'weather' collection (PUT http://localhost:3000/weather/:id)
app.put('/weather/:id', async (req, res) => {....
字符串
SCHEMA:
const mongoose = require('mongoose');
const weatherSchema = mongoose.Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
required: true
},
"Device Name": {
type: String,
required: true
},
"Precipitation mm/h": {
type: Number,
required: true
},
Time: {
type: Date,
required: true
},
Latitude: {
type: Number,
required: true
},
Longitude: {
type: Number,
required: true
},
"Temperature (°C)": {
type: Number,
required: true
},
"Atmospheric Pressure (kPa)": {
type: Number,
required: true
},
"Max Wind Speed (m/s)": {
type: Number,
required: true
},
"Solar Radiation (W/m2)": {
type: Number,
required: true
},
"Vapor Pressure (kPa)": {
type: Number,
required: true
},
"Humidity (%)": {
type: Number,
required: true
},
"Wind Direction (°)": {
type: Number,
required: true
}
});
const Weather = mongoose.model('Weather', weatherSchema, 'weather'); // 'weather' is the collection name
module.exports = Weather;
型
输入
PUT http://localhost:3000/weather/updateMultiple
[
{
"_id": "65714e17a36f8c7d905f599f",
"Device Name": "Updated_Device_UPDATE_MULTIPLE_1",
"Humidity (%)": 75.0
},
{
"_id": "65714e17a36f8c7d905f59a0",
"Device Name": "Updated_Device_UPDATE_MULTIPLE_2",
"Humidity (%)": 80.0
}
]
型
1条答案
按热度按时间b4wnujal1#
只是一个愚蠢的错误。我没有意识到nodemon没有运行,我不得不手动重启服务器来更新所有内容。所以这里的代码实际上是工作的,只是本质上不是活的。