Home > Software design >  Create multiple documents from an array of values in Mongo DB
Create multiple documents from an array of values in Mongo DB

Time:06-23

I'm new to MongoDB and I know this might sound silly to many but is there a way(s) where you can create multiple documents from an array of values. I have written some code for this, but is there any other efficient/shorter way of doing that.

tags.map(async tag => {
    const tagDoc = await TagModel.create({ tag, postID })
})

Tag Schema -

const tagSchema = new mongoose.Schema({
    postID: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Post",
    }],
    tag: {
        type: String,
        required: true,
    },
}, { timestamps: true })

CodePudding user response:

Case 1 : Storing Tags in Same Collection

in mysql you have to store tags in different table , but in mongodb you can use same collection to store tags as array of string

in your post schema :

const postSchema = new mongoose.Schema({
    ...
    tags: {
        type: [String],
        required: true,
    }
});

when saving post =>

let post = new Post();
...
post.tags = req.body.tags;   // ["Tag1","hello","Testing"];
await post.save();

Case 2 : Storing Tags in Different Collection

if you want to store tags in different collection Tag , then you can use Mongoose InsertMany()

   let tags = req.body.tags ;  // ["Tag1","hello","Testing"];
   tagsArray = tags.map((t)=> { return {postID:post._id , tag:t}});
   let tagsSaved = await Tag.insertMany(tagsArray);
   console.log('tagsSaved=',tagsSaved);
  • Related