Node.js中如何根据多picture对象存储多个MongoDB文档?
Solution to Save Multiple Picture Entries as Separate MongoDB Documents
Your current code is looping over the entire request body object (which includes keys like user_id, picture, etc.) instead of iterating through the picture array in the request. That’s why you’re not getting multiple documents created. Here’s how to fix it:
Step-by-Step Fix
- Extract shared fields from the request body (
user_id,mimetype,device_platform). - Loop through each individual picture object in the
picturearray. - For each picture, create a new
UserStatusModelinstance that combines the shared fields with the picture-specific data. - Save each document (you can do this sequentially or in parallel for better performance).
Corrected Code (Sequential Save)
// Extract shared fields and picture array from request body const { user_id, mimetype, device_platform, picture } = req.body; const userRecords = []; // Loop through each picture in the array for (const pic of picture) { try { const record = await new UserStatusModel({ user_id, mimetype, device_platform, // Spread picture-specific fields (height, preview, url, width) ...pic }).save(); userRecords.push(record); } catch (err) { // Handle errors for individual picture saves if needed console.error(`Failed to save picture: ${err.message}`); } } // userRecords contains all successfully saved documents
Optimized Version (Parallel Save with Promise.all)
If you have a large number of pictures, using Promise.all will save all documents in parallel, which is faster than sequential saves:
const { user_id, mimetype, device_platform, picture } = req.body; // Create an array of save promises for each picture const savePromises = picture.map(pic => new UserStatusModel({ user_id, mimetype, device_platform, ...pic }).save() ); try { // Wait for all save operations to complete const userRecords = await Promise.all(savePromises); // All documents saved successfully } catch (err) { // Note: Promise.all rejects immediately if any single save fails console.error(`Error saving pictures: ${err.message}`); }
Key Notes
- Error Handling: The sequential version lets you handle errors per picture (so one failed save doesn’t block others), while
Promise.allrejects as soon as any save fails. Choose based on your error tolerance needs. - Schema Validation: Ensure your
UserStatusModelschema accepts the picture-specific fields (height,preview,url,width) as valid properties. - Destructuring: Using
...picsimplifies passing all picture-specific fields into the model without listing them individually.
内容的提问来源于stack exchange,提问作者Mic
相关产品推荐
相关产品推荐

