使用Mongoose+Node.js更新MongoDB对象数组及设置初始权重问题
previousWeight Initialization When Adding Exercises Got it, let's fix this together! You already have the logic to add exercises to the array, so we just need to tweak that update operation to set previousWeight to 0 at the same time. Here are a couple of straightforward approaches:
1. Directly Include $set in Your Update Query
This is the simplest way—just add a $set clause right alongside your $push when updating the document. Let's assume your Mongoose model looks something like this first:
// Example User Schema const UserSchema = new mongoose.Schema({ exercises: [{ name: String, weight: Number, // other exercise fields... }], previousWeight: Number }); const User = mongoose.model('User', UserSchema);
Then modify your existing update code to include the $set for previousWeight:
const userId = "your-user-id-here"; const newExercise = { name: "Squats", weight: 120 }; User.findOneAndUpdate( { _id: userId }, { $push: { exercises: newExercise }, // Your existing exercise push $set: { previousWeight: 0 } // Sync set to 0 }, { new: true, runValidators: true } // Return updated doc + enforce schema rules ) .then(updatedUser => console.log("Updated user:", updatedUser)) .catch(err => console.error("Update error:", err));
This ensures every time you add an exercise, previousWeight gets set to 0 immediately.
2. Use a Mongoose Pre-Hook for Automatic Sync
If you want this behavior to happen automatically every time an exercise is added (without writing $set every time), you can add a pre-update hook to your schema:
UserSchema.pre("findOneAndUpdate", function(next) { // Check if we're pushing a new exercise if (this._update.$push && this._update.$push.exercises) { // Ensure $set exists, then set previousWeight to 0 this._update.$set = this._update.$set || {}; this._update.$set.previousWeight = 0; } next(); });
Now any findOneAndUpdate call that pushes to the exercises array will automatically set previousWeight to 0—no extra code needed in your update logic!
Quick Notes:
- If
previousWeightmight already have a value, this will overwrite it—make sure that's the behavior you want. - If your schema has validations for
previousWeight(likerequired: true), addingrunValidators: truein the update options ensures the 0 value passes those checks.
内容的提问来源于stack exchange,提问作者Gromit




