使用Mongoose 5.0.1向MongoDB数组推送对象时出错求助
Hey there! Let's figure out why you're running into errors when pushing an object into a MongoDB array using Mongoose 5.0.1. Based on the code snippets you shared, here are the most common issues and fixes to try out:
First off, make sure your testModel schema correctly defines the array field you're trying to push to. If the field isn't set as an array type, Mongoose will reject the $push operation outright. For example:
// Correct schema setup for an array of objects const testSchema = new mongoose.Schema({ testTitle: String, // Use a nested schema for strict validation (recommended) questions: [{ questionText: String, options: [String], correctAnswer: String // Add any other fields your quesObj includes }] // Or use [Object] if you don't need strict validation (less ideal) // questions: [Object] }); const testModel = mongoose.model('Test', testSchema);
If your schema doesn't mark questions as an array, that's almost certainly a root cause.
It looks like you're starting with testModel.findOne, but there are two reliable ways to push objects to an array—pick the one that fits your flow:
Option 1: Use findOneAndUpdate (Efficient & Avoids Race Conditions)
This method queries and updates the document in one go, which is better for performance and prevents conflicts if multiple requests hit at the same time:
eventEmitter.on('save question db', function(quesObj, testTitle) { testModel.findOneAndUpdate( { testTitle: testTitle }, // Match the test by title { $push: { questions: quesObj } }, // Push the new question object { new: true, upsert: false } // new: true returns the updated document; upsert: true creates a test if none exists (optional) ) .then(updatedTest => { if (!updatedTest) { console.log(`No test found with title: ${testTitle}`); // Optional: Create a new test if needed // const newTest = new testModel({ testTitle, questions: [quesObj] }); // return newTest.save(); } else { console.log('Question added successfully:', updatedTest); // You could emit a success event back to the client here // socket.emit('question saved', updatedTest); } }) .catch(err => { console.error('Error pushing question:', err); // Send error feedback to the client // socket.emit('save error', err.message); }); });
Option 2: Find First, Then Save (For More Control)
If you need to run additional logic before saving, use findOne with async/await (or promises) to avoid undefined document errors:
eventEmitter.on('save question db', async function(quesObj, testTitle) { try { const test = await testModel.findOne({ testTitle: testTitle }); if (!test) { console.log(`Test "${testTitle}" doesn't exist yet!`); // Optional: Create a new test document // const newTest = new testModel({ testTitle, questions: [quesObj] }); // await newTest.save(); return; } test.questions.push(quesObj); await test.save(); console.log('Question saved successfully'); } catch (err) { console.error('Error during save:', err); } });
Critical note: Always handle async operations properly with async/await or .then()—if you skip this, your code will run synchronously and test will be undefined when you try to push, causing an error.
quesObj Matches Your Schema Make sure the quesObj sent from the client matches the structure defined in your schema. For example, if your schema requires a questionText field but the client sends an object without it, Mongoose's validation will fail (if enabled). You can either:
- Adjust the client to send the correct fields, or
- Temporarily set
strict: falsein your schema (not recommended long-term, as it bypasses validation)
If none of the above fixes work, always log the full error message in your catch block. Common errors include:
Cast to Array failed for value...: Means your schema doesn't define the field as an arrayDocument not found: Your query fortestTitleisn't matching any documentsValidation failed...:quesObjdoesn't meet schema requirements
The error message will point you directly to the problem!
Mongoose 5.0.1 is a fairly old version (released in 2018). There were some known bugs with array operations in early 5.x versions. If you've tried everything else, upgrading to a newer 5.x release (like 5.13.x) might resolve the issue.
内容的提问来源于stack exchange,提问作者Salmaan shaik

