I am creating a simple blog which have posts containing tags.
var postSchema = new Schema ({
title: { type: String, required: true },
content: { type: String, required: true },
tags: [{ type: Schema.Types.ObjectId, ref: 'Tag' }]
});
When a user publishes a post I get the tags as an array of tag names. How can I loop through these tags and create them and add them to the post when it is first saved?
I have tried this:
var post = Post({
title: data.title,
content: data.content
});
data.tags.forEach(function(name) {
Tag.findOrCreate({ name: name }, function(err, tag, created) {
post.tags.push(tag);
post.save(function(err) {
if (err) throw err;
console.log('Post saved!');
});
});
});
But that forces me to save the post again for each tag. Is there a way to only save once?