使用ES8 async/await的Express Router删除接口Mongoose查询返回null问题
Input.findById() Returns Null in Async/Await Express Delete Route Let's break down why your Input.findById() is returning null even though you're receiving the ID correctly. Here are the most likely culprits and fixes:
1. Variable Name Collision (The Most Probable Issue)
Look at this line in your code:
const Input = await Input.findById(params.id);
You're reusing the same Input name for both your Mongoose Model and the local variable storing the fetched document. This causes a scope conflict—by the time Input.findById runs, Input is already being hoisted as the local variable, not your original Model.
Fix: Rename the local variable to something distinct:
const inputDocument = await Input.findById(params.id);
2. Invalid ObjectID Format
Even if you're getting the ID from params, it might not be a valid Mongoose ObjectID. Mongoose expects IDs to be 12-byte binary strings or 24-character hex strings.
Fix: Add a validation check before querying:
const mongoose = require('mongoose'); if (!mongoose.Types.ObjectId.isValid(params.id)) { return res.status(400).json({ success: false, message: 'Invalid ID format' }); }
If your schema uses a custom non-ObjectID primary key, make sure you've configured the Model correctly (e.g., set _id: false and define your own id field).
3. The Document Actually Doesn't Exist
It's possible the ID you're passing doesn't correspond to any document in your database. Double-check by querying your database directly:
In MongoDB Shell:
db.inputs.findOne({ _id: ObjectId("your-id-here") })
Replace inputs with your actual collection name. If this returns nothing, the document was either deleted or never existed.
4. Incorrect Model Import/Name
Verify that your Input Model is imported correctly. A typo in the import path or variable name (e.g., input instead of Input) could lead you to query the wrong Model entirely.
Corrected Full Code Example
Here's your route with all fixes applied:
router.delete('/:id', async ({ params }, res) => { try { // Validate ID format first const mongoose = require('mongoose'); if (!mongoose.Types.ObjectId.isValid(params.id)) { return res.status(400).json({ success: false, message: 'Invalid ID format' }); } // Fetch document with non-conflicting variable name const inputDocument = await Input.findById(params.id); // Explicitly check if document exists if (!inputDocument) { return res.status(404).json({ success: false, message: 'Document not found' }); } await inputDocument.remove(); res.json({ success: true }); } catch (error) { console.error('Delete error:', error); // Log error for debugging res.status(500).json({ success: false, message: 'Server error occurred' }); } });
内容的提问来源于stack exchange,提问作者Alexander

