基本上,我想创建一个帖子,该帖子的作者为用户名,即创建者。我还希望将Post推入用户模型所拥有的帖子数组中,即引用“ Post”。
我一直在谷歌搜索和观看youtube视频,但我仍然不明白该怎么做,我也读过有关填充的信息,但是我想创建一个新帖子,并让作者作为用户名,我希望将帖子推送到用户拥有的帖子数组中。
我将如何去做?
这是帖子创建控制器
exports.postCreatePost = (req, res, ) => {
const {
title,
description,
context
} = req.body;
const post = new Post({
title,
description,
context,
author:
})
}
这是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();
答案 0 :(得分:0)
要么让客户端向您发送用户名/ id,然后从req.body中获取它,要么在您对用户进行身份验证时,只需将对用户的引用传递给请求的正文。
例如,当客户端为您提供ID /用户名时,您可以执行以下操作
const post = new Post({
title,
description,
context,
author: req.body.username or req.body.id
})
如果要推送,请使用此
await findOneAndUpdate({_id: req.body.id}, {
"$push":
{
"posts": post._id
}
})