Home > database >  How to save multiple url String Array in MongoDb
How to save multiple url String Array in MongoDb

Time:06-21

I'm trying to save image urls from cloudinary to mongoDb, but it's not working.I want to add the url string array to the portfolio field.

Schema :
const ResumeSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },    
portfolio: [
  {
    type: String,
    required: false,
  },
],
    createdAt:{
        type:Date,
        default: Date.now
    },
});
const Resume=mongoose.model("Resume", ResumeSchema,'resume');

module.exports=Resume

controller :

exports.createPortfolio = asyncHandler(async (req, res, next) => {
        const _id = req.params.id;
        const label = 'Portfolio';
        // If File not found
        if (req.files) { 
            const imageURIs = []; // array to hold the image urls
            const files = req.files; // array of images
            for (const file of files) {
                const { path } = file;
                imageURIs.push(path);
            };
               console.log(imageURIs)    
        
          Resume.findOne(
            {
              email: email,     
            },
            { $set: { portfolio: imageURIs} },
            {
              new: true,
              fields: {
                portfolio: 1,
              },
            }
          ).exec((err, results) => {
            if (err) throw err;
            res.json(results);
          });
        }
      });
      

console.log(imageURL) array has the following output :

[
  'https://res.cloudinary.com/wo/image/upload/v1655533057/avatar/2022-06-18T06-17-33.914Z22.jpg.png',
'https://res.cloudinary.com/wo/image/upload/v1655533067/avatar/2022-06-18T06-17-33.919Z14-1.png.png'
]

I want a situation where the field is

CodePudding user response:

Try to use the findOneAndUpdate function with $push and $each to add all path in your array:

exports.createPortfolio = asyncHandler(async (req, res, next) => {
  const _id = req.params.id;
  const label = 'Portfolio';
  // If File not found
  if (req.files) {
    const imageURIs = []; // array to hold the image urls
    const files = req.files; // array of images
    for (const file of files) {
      const { path } = file;
      imageURIs.push(path);
    }
    console.log(imageURIs);

    Resume.findOneAndUpdate(
      {
        email,
      },
      { $push: { portfolio: { $each: imageURIs } } },
      {
        new: true,
        fields: {
          portfolio: 1,
        },
      }
    ).exec((err, results) => {
      if (err) throw err;
      res.json(results);
    });
  }
});
  • Related