author: {
type : Scema.Types.ObjectId,
ref : 'User',
required : true,
},
const author = await User.find({
shortId : req.user.shortId,
});
if(!author){
throw new Error("No User");
}
await Post.create({
title,
content,
author.
});
게시글 find시 populate를 추가하여 ObjectID로 저장된 author를 각 게시글에 주입
사용시 post.author.{field}로 사용 가능
--- ./routes/posts.js ---
router.get('/', ... {
...
const posts = await Post
.find({})
...
.populate('author');
res.render('posts/list', { posts });
--- ./views/posts/list.pug ---
...
td post.author.name
const post = await Post.find({
shortId,
}).populate('author');
if (post.author.shortId !== req.user.shortId) { throw new Error('Not Authorized');
}
author: {
type: Schema.Types.ObjectId, ref: 'User',
required: true,
index: true,
},
--- ./routes/users.js ---
...
router.get('/:shortId/posts', ... => {
...
const { shortId } = req.params;
const user = await User.find({ shortId }); const posts = await Post
.find({ author: user })
.populate('author');
res.render('posts/list', { posts, user });
}); ...
h2= user ? `${user.name}의 게시글`: "전체 게시글" ...
td: a(href=`/users/${post.author.shortId}`)
= post.author.nam