2

I want to achive funcionality, where user in the frontend writes how many posts he want to insert in the database.. He can write 1, 5, 10, 15,.. up to 50 same posts.

The posts are then the SAME in the database, just this manually generated _id is different.

At first I thought that it can be done just like that:

exports.addPost = async (req: any, res: any) => {
  try {
    const newPost = new Post({
      title: req.body.title,
      description: req.body.description,
      author: req.body.author,
    });
    for (let i: number = 0; i < 5; i++) {
      await newPost .save();
    }
    res.status(201).json(newContainer);
  } catch (err) {
    res.status(400).json(err);
  }
};

Post schema:

const PostSchema = new mongoose.Schema({
  title: { type: String, required: true },
  description: { type: String, required: true },
  author: {
    type: Schema.Authors.ObjectId,
    ref: "Authors",
    required: true,
  },
});

module.exports = mongoose.model("Posts", PostSchema);

but I am not sure, if this is really the way to go.. What is some good practice for this (assuming that the number 5 in for loop will come in req.body.. So from user input.

Thanks

1 Answer 1

2

You can just use the following code:

try {
    await Post.create(
      new Array(5).fill(true).map((_) => ({
        title: req.body.title,
        description: req.body.description,
        author: req.body.author,
      }))
    );
    res.status(201).json(newContainer);
  } catch (err) {
    res.status(400).json(err);
  }

model.create does accept passing an array of (new) documents to it. By mapping a new array of size 5 (or depending on user input) to your custom document and passing it to the create function will result in multiple documents created. A huge benefit is that you only have to perform one single database call (and await it).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. It works! If you think my question could help someone, feel free to upvote it. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.