Home > front end >  Try storing a string array of urls using mongoose
Try storing a string array of urls using mongoose

Time:01-27

I'm trying to store an object in MongoDB using react and express. The object contains individual fields and an array of strings. If I send the whole thing to the backend using FormData, MongoDB only adds one line to the string array and not two as desired (to stay with the example). How do I fix that?

This is the main code:

let data = new FormData();
data.append("articelTitle", title);
data.append("articelImages", JSON.stringify(uploadImages));
data.append("artikelDescription", descEditor);
data.append("articelPrice", price);
data.append("articelConditions", condition);
try {
  axios
    .post("http://localhost:8800/api/articel/new", data, {
      headers: {
        "Content-Type": "application/json",
      },
    })
    .then((res) => {
      console.log(res.data);
    });
} catch (error) {
  console.log(error);
}

Output in the backend controller function 'newArticel':

[
 'https://firebasestorage.googleapis.com/...',
 'https://firebasestorage.googleapis.com/...'
]

Express:

export const newArticel = async (req, res) => {
try {
console.log(JSON.parse(req.body.articelImages));

const newArt = new Art({
  ...req.body,
  $push: { articelImages: JSON.parse(req.body.articelImages) },
});

const art = await newArt.save();
res.status(200).json(art);
 } catch (error) {
   console.log(error);
 }
};

And that's what I get.

enter image description here

But I need

articelImages[0]:"https://...."

articelImages1: "https://..."

Article scheme only the most necessary:

const ArticelSchema = new mongoose.Schema(
 {
articelTitle: {
  type: String,
  require: true,
},
articelImages: {
  type: [String],
  require: true,
},
artikelDescription: {
  type: String,
  require: true,
  },
 ...
 },

);

CodePudding user response:

Since req.body.articleImages is an array of strings, you need to push each element in the array to the MongoDB using $each identifier.

const newArt = new Art({
  ...req.body,
  $push: { articelImages: {$each: JSON.parse(req.body.articelImages)} },
});
  • Related