Node.js中Mongoose User模型Hobbies数组更新异常问题求助
hobbies Field Format in Your Patch API Hey there, let's sort out why your hobbies field is showing up as a string inside an array instead of a clean array like intrestedIn. Looking at your response, the issue is clear: your backend is receiving a nested JSON string/object for hobbies and just assigning it directly, instead of extracting the actual array.
What's Going Wrong?
Your current response shows:
"hobbies": [ "{\"hobbies\":[\"dancing\",\"running\"]} " ]
This means the req.body.hobbies value coming in is either:
- A JSON string like
"{\"hobbies\":[\"dancing\",\"running\"]}", or - A nested object like
{ hobbies: ["dancing", "running"] }
Your code is just taking this value and assigning it to user.hobbies directly, which is why it's ending up as a string inside an array (or a nested object saved incorrectly).
How to Fix It
We need to adjust your code to parse or extract the actual array from the incoming hobbies value. Here are the steps to fix this:
1. Modify the Backend Code to Process hobbies
Update your forEach loop to handle the hobbies field specifically:
updates.forEach((update) => { if (update === 'hobbies') { let hobbiesData = req.body[update]; // Handle case where incoming value is a JSON string (trim extra spaces first) if (typeof hobbiesData === 'string') { try { hobbiesData = JSON.parse(hobbiesData.trim()); } catch (e) { return res.send({ error: "Invalid hobbies format" }); } } // Extract the array if it's nested in an object, else use the value directly user[update] = hobbiesData.hobbies || hobbiesData; } else { user[update] = req.body[update]; } })
2. Double-Check Your Mongoose Model
Ensure your User model defines hobbies as an array type so Mongoose stores it correctly:
const userSchema = new mongoose.Schema({ // ... other fields hobbies: [String], // This enforces storage as an array of strings intrestedIn: [String] });
3. (Optional) Fix the Frontend Request (If You Control It)
If you can adjust the frontend, send hobbies as a direct array instead of a nested object/string. Your request body should look like this:
{ "userId": "5ec71c43026b2f1d640b657f", "hobbies": ["running", "dancing"] }
With this, your original code would work without extra parsing steps.
Testing the Fix
After making these changes, send a patch request with the correct hobbies format, and your response should return the clean array you expect:
{ "user": { "intrestedIn": [ "Female" ], "hobbies": [ "dancing", "running" ], "_id": "5ec71c43026b2f1d640b657f" } }
内容的提问来源于stack exchange,提问作者Amit Ratheee

