我有一个帖子集合表,其中包含指向用户集合的链接。我需要帮助来获取由用户创建的帖子数组。我的意思是包含帖子和创建该帖子的用户的对象数组。 它应该返回 [{post1,user who created post1},{post2,user who created post2},{post3,user who created post3}] 后期模特
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PostSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
category: {
type: String,
required: true
},
description: {
type: String,
required: true
},
title: {
type: String,
required: true
},
image: {
type: String
},
date: {
type: Date,
default: Date.now
},
avatar: {
type: String
},
likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'users'
}
}
],
comments: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
text: {
type: String,
required: true
},
name: {
type: String
},
avatar: {
type: String
},
date: {
type: String,
default: Date.now
}
}
],
date: {
type: String,
default: Date.now
}
});
module.exports = Post = mongoose.model('post', PostSchema);
发布路线
router.get('/posts', auth, async (req, res) => {
try {
const post = await Post.find().sort({ date: -1 });
console.log('post', post);
res.json(post);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
} });