如何在Mongoose中向文档对象内的数组执行$push操作?
Got it, let's fix that $push issue you're hitting. The problem with your current approach is that you're wrapping the $push inside the rating object, which tells Mongoose you want to overwrite the entire rating field instead of modifying its nested usersRated array.
Here's the correct way to target that nested array:
1. Using Direct Update with $push
You need to use a dot-separated path to point directly to the usersRated array inside the rating object. Here's how it looks in practice:
// Using updateOne (callback style) YourModel.updateOne( { _id: yourDocumentId }, // Your query to find the target document { $push: { "rating.usersRated": data.userId } }, // The correct update operation (err, updateResult) => { if (err) { console.error("Failed to push userId:", err); } else { console.log("Successfully added userId to usersRated:", updateResult); } } ); // Or with async/await (cleaner for modern code) try { const updateResult = await YourModel.updateOne( { _id: yourDocumentId }, { $push: { "rating.usersRated": data.userId } } ); console.log("Successfully added userId:", updateResult); } catch (err) { console.error("Error pushing userId:", err); }
2. Alternative: Fetch the Document First, Modify, Then Save
If you prefer working with the document instance directly (useful if you need to run additional logic on the document), you can do this:
try { const doc = await YourModel.findById(yourDocumentId); doc.rating.usersRated.push(data.userId); // Push directly to the nested array await doc.save(); // Save changes back to the database console.log("UserId added successfully!"); } catch (err) { console.error("Error updating document:", err); }
Quick Note on Schema Best Practices
To avoid unexpected issues later, it's a good idea to explicitly define the type for your usersRated array (especially if it's storing user ObjectIds):
const yourSchema = new mongoose.Schema({ rating: { usersRated: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }], // Specify type for user IDs rating: { type: Number, default: 0 } // Add a default value if needed } });
That should get your $push working as expected!
内容的提问来源于stack exchange,提问作者Michael Kutateladze

