我正在嘗試制作一個社交媒體應用程式,陷入了這種我不知道如何與用戶一起發布帖子的情況,
我正在嘗試獲取帖子集合中存在的所有帖子以及每個帖子的用戶資訊,我曾經有一個函式可以找到用戶,回傳它,并將其添加到前端的帖子 JSON 中,但我想在那里必須是使用內部連接等更好的方法,所以在前端我可以回圈for post in posts
訪問帖子結果,并訪問資訊,如post.content, post.author.avatar, post.author.username...
這是帖子架構:
const { Schema, model } = require('mongoose');
const PostSchema = new Schema({
userId: {
type: String,
required: true,
},
content: {
type: String,
required: true,
max: 500,
},
likes: {
type: Array,
default: []
}
},
{ timestamps: true }
)
const PostModel = model('post', PostSchema);
module.exports = PostModel;
這是我用來創建它的方法(我提供了用戶 ID 和內容):

這是獲取所有帖子的api方法
//get (all) posts
router.post('/feed/all', async (req, res) => {
try {
let feed = [];
const currentUser = await getPostUser(req.body.userId)
if (!currentUser)
return res.status(404).json({ error: 'User not found' });
// my posts
const userPosts = currentUser ? (await Post.find({ userId: currentUser._id }).sort({ createdAt: -1 })) : {};
userPosts.forEach(element => {
feed.push(element)
});
// followed posts
await Promise.all(
currentUser.followings.map(async (followedId) => {
let postUser = await getPostUser(followedId);
let posts = (postUser) ? (await Post.find({ userId: followedId }).sort({ createdAt: -1 })) : {};
posts.forEach(element => {
feed.push(element)
});
})
);
res.json(feed.sort(createdAt));
} catch (error) {
res.status(500).json({ error: error, message: 'drrr' })
}
})
用戶架構:
const { Schema, model } = require('mongoose');
const UserSchema = new Schema(
{
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
},
firstname: {
type: String,
required: true,
},
lastname: {
type: String,
required: true,
},
email: {
type: String,
required: true
},
avatar: {
type: String,
default: "https://w7.pngwing.com/pngs/419/473/png-transparent-computer-icons-user-profile-login-user-heroes-sphere-black-thumbnail.png"
},
bio: {
type: String,
default: ""
},
followers: {
type: Array,
default: []
},
followings: {
type: Array,
default: []
},
isAdmin: {
type: Boolean,
default: false
},
isMod: {
type: Boolean,
default: false
}
},
{ timestamps: true }
)
const UserModel = model('user', UserSchema);
module.exports = UserModel;
uj5u.com熱心網友回復:
- 首先,您可以像這樣更改帖子架構以參考用戶架構
const { Schema, model } = require('mongoose');
const PostSchema = new Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
required:true
},
content: {
type: String,
required: true,
max: 500,
},
likes: {
type: Array,
default: []
}
},
{ timestamps: true }
)
const PostModel = model('post', PostSchema);
module.exports = PostModel;
- 然后我們將使用populate方法回傳帶有用戶資訊的帖子,如下所示
//get (all) posts
router.post('/feed/all', async (req, res) => {
try {
let feed = [];
const currentUser = await getPostUser(req.body.userId)
if (!currentUser)
return res.status(404).json({ error: 'User not found' });
// my posts
if(currentUser){
const userPosts =await Post
.find({ userId: currentUser._id }).sort({ createdAt: -1 })
.populate('userId','_id username firstname lastname email avatar bio followers followings')
}
// followed posts
await Promise.all(
currentUser.followings.map(async (followedId) => {
let postUser = await getPostUser(followedId);
let posts = (postUser) ? (await Post.find({ userId: followedId }).sort({ createdAt: -1 })) : {};
posts.forEach(element => {
feed.push(element)
});
})
);
res.json(feed.sort(createdAt));
} catch (error) {
res.status(500).json({ error: error, message: 'drrr' })
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406239.html
標籤:
