[英]How to populate the users with the posts that have the user's id in mongoose?
我正在创建我的第一个 MERN 应用程序,我遇到了这个问题:我有包含用户 ID 的帖子:
{
"reward": {
...
},
"_id": "5eb2d90d7d56c415cc4d5f97",
"user": "5eabbb85b8814723fcee0f01",
"text": "Body text hihi hahha",
"createdAt": "2020-05-06T15:34:37.439Z",
"__v": 0
}
在帖子 controller 中创建时,我确实设法自动将用户 ID 添加到帖子中。 现在的问题是我不知道应该在哪里以及如何将创建的帖子的 ID 推送到用户 model 的帖子数组中。 这是用户 model:
username: {
type: String,
required: [true, "Username is required"],
unique: true,
trim: true,
minlength: 3,
maxlength: 15,
},
email: {
type: String,
required: [true, "Email is required"],
unique: true,
},
role: {
type: String,
enum: ["user"],
default: "user",
},
cards: [
{
type: mongoose.Schema.ObjectId,
ref: "Card"
},
],
在“卡片”所在的地方,我想在用户字段中拥有包含用户 ID 的帖子的 ID。 这是帖子 model:
user: String,
text: {
type: String,
},
reward: {
...
},
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true
},
这是用于将帖子保存到数据库的 controller:
exports.addCard = asyncHandler(async (req, res, next) => {
//Add user to req.body
req.body.user = req.user.id;
const card = await Card.create(req.body);
res.status(201).json({
success: true,
message: 'Card created',
data: card
});
});
我猜它应该在创建帖子时发生,例如在当前登录用户的用户模式中的帖子数组中推送该帖子 ID? 如何正确存档?
您可以进行第二次查询以插入_id
。
确保$match
处的_id
是 ObjectId,如ObjectId("5d345234daa45")
而不是5d345234daa45
exports.addCard = asyncHandler(async (req, res, next) => {
//Add user to req.body
req.body.user = req.user.id;
const card = await Card.create(req.body);
const id = card._id; // this should be your _id, check with console.log() if this is your _id
//dont forget to import your model
await User.update({ _id: mongoose.Types.ObjectId(req.body.user) },
{
$push: {
cards: id
}
});
res.status(201).json({
success: true,
message: 'Card created',
data: card
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.