I'm trying to wrap my head around using async/await with promises and mongoose references.
The code below almost works: the 3 posts get created and so do the comments for the first one, but none of the comments for the third post get created.
I'm assuming this is because I'm not putting the async/awaits in the right place, but I don't know how to organize the code so it works.
const seedData = [
{
title: 'Post 1',
content: `beard sustainable Odd Future pour-over Pitchfork DIY fanny pack art party`,
comments: [
{ content: 'comment1 1' },
{ content: 'comment1 2' },
{ content: 'comment1 3' }
]
},
{
title: 'Post 2',
content: `flannel gentrify organic deep v PBR chia Williamsburg ethical`,
comments: []
},
{
title: 'Post 3',
content: `bag normcore meggings hoodie polaroid gastropub fashion`,
comments: [{ content: 'comment3 1' }, { content: 'comment3 2' }]
}
];
async function createPostsAndComments() {
let promises = [];
// delete existing documents
Post.remove(() => {});
Comment.remove(() => {});
// create three posts along with their comments
seedData.forEach(async postData => {
// create the post
let post = new Post({
_id: new mongoose.Types.ObjectId(),
title: postData.title,
content: postData.content
});
// wait for the promise returned by `post.save`
promises.push(
post.save(error => {
if (error) console.log(error.message);
// create the comments of the current post
postData.comments.forEach(async commentData => {
const comment = new Comment({
content: commentData.content,
post: post._id
});
// wait for the promise from `comment.save`
promises.push(
comment.save(error => {
if (error) console.log(error.message);
})
);
});
})
);
});
return Promise.all(promises);
}
async function initSeed() {
mongoose.connect(process.env.DATABASE, { useMongoClient: true });
await createPostsAndComments();
mongoose.connection.close();
}
initSeed();
In case it's useful, here are the schemas:
import mongoose from 'mongoose';
exports.commentSchema = new mongoose.Schema(
{
content: {
type: String,
required: true
},
post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }
},
{
toJSON: { virtuals: true }, // TODO: what's this?
toObject: { virtuals: true }
}
);
exports.Comment = mongoose.model('Comment', exports.commentSchema);
import mongoose from 'mongoose';
exports.postSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
title: {
type: String,
required: true
},
content: {
type: String,
required: true
},
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
exports.Post = mongoose.model('Post', exports.postSchema);