You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Extract shared fields from the request body (user_id, mimetype, device_platform).
  2. Loop through each individual picture object in the picture array.
  3. For each picture, create a new UserStatusModel instance that combines the shared fields with the picture-specific data.
  4. 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.all rejects as soon as any save fails. Choose based on your error tolerance needs.
  • Schema Validation: Ensure your UserStatusModel schema accepts the picture-specific fields (height, preview, url, width) as valid properties.
  • Destructuring: Using ...pic simplifies passing all picture-specific fields into the model without listing them individually.

内容的提问来源于stack exchange,提问作者Mic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:24:05