Home > Back-end >  Insert same records multiple times to the Mongo database with NodeJs
Insert same records multiple times to the Mongo database with NodeJs

Time:10-13

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

CodePudding user response:

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).

  • Related