我正在嘗試使用 MERN 堆棧制作一個應用程序。當我嘗試將用戶添加到當前數據庫時,它返回“CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model "Project"我做錯了什么?”API.jsimport axios from "axios";export default { updateUser: function (id, data) { return axios.put("/api/user/" + id, data); },}apiRoute.jsapp.put("/api/project/:id/add-user", async (req, res) => { // Find the project that was created and update it with a user // console.log("Hello") try { const dbProject = await db.Project.findOneAndUpdate({ _id: req.params.id }, { // Append the User to the Project object $push: { users: req.body.userId } }, { new: true }); // Send the request back to the front end res.send(dbProject) } catch (error) { console.log({ "PUT - Project Add User": error }) res.send(error) } });項目.js(模型)const mongoose = require('mongoose');const { Schema } = mongoose;const projectSchema = new Schema({ project_name: { type: String, unique: true }, team_lead: String, description: String, tags: String, location: String, num_members: Number, // image: String, users: [ { type: Schema.Types.ObjectId, ref: "users" } ]});const Project = mongoose.model('Project', projectSchema);module.exports = Project;
CastError:模型“”的路徑“_id”處的值“未定義”轉換為 ObjectId 失敗
慕后森
2023-09-21 10:51:13