My goal is to create a Post with the author being the user who created it and have the Post added to the array of posts in the user model that references "Post". Despite searching and watching tutorials, I'm still struggling to understand how to achieve this. I've come across the "populate" method, but I specifically want to create a new post with the author as the user's name and have it added to the user's posts array. How should I approach this?
Here is the post creation controller:
exports.postCreatePost = (req, res) => {
const {
title,
description,
context
} = req.body;
const post = new Post({
title,
description,
context,
author:
})
}
And here is the model.js:
const mongoose = require("mongoose"),
Schema = mongoose.Schema,
bcrypt = require("bcryptjs");
const postSchema = new Schema({
title: String,
description: String,
context: String,
author: {
type: Schema.Types.ObjectId,
ref: "User"
}
});
const userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true
},
posts: [{
type: Schema.Types.ObjectId,
ref: "Post"
}]
});
userSchema.pre("save", async function save(next) {
const user = this;
if (!user.isModified("password")) return next();
const hashedPassword = await bcrypt.hash(user.password, 10);
user.password = hashedPassword;
next();
});
const Post = mongoose.model("Post", postSchema);
const User = mongoose.model("User", userSchema);
const userId = new mongoose.Types.ObjectId();