Users model:
const {Schema, model, Types} = require("mongoose");
const schema = new Schema({
name: {type: String, required: true},
email: {type: String, required: true, unique: true},
password: {type: String, required: true},
posts: [{type: Types.ObjectId, ref: "Post"}],
avatar: {type: String, required: true, default: "https://cdn.pixabay.com/photo/2013/07/13/12/07/avatar-159236_960_720.png"},
friends: [{type: Types.ObjectId, ref: "User"}],
subscribes: [{type: Types.ObjectId, ref: "User"}]
});
module.exports = model("User", schema);
Posts model:
const {Schema, model, Types} = require("mongoose");
const schema = new Schema({
title: {type: String, required: true},
description: {type: String, required: true},
owner: {type: Types.ObjectId, ref: "User"},
createdAt: {type: Date, required: true, default: Date.now},
coverImage: {type: String, default: "no"},
likes: {type: Number, default: 0, required: true},
comments: [{type: Types.ObjectId, ref: "Comment"}],
views: {type: Number, default: 0}
})
module.exports = model("Post", schema);
Posts controller:
const Post = require("../models/Post");
class Postscontroller {
async getUserPosts(req, res) {
try {
const posts = await Post.find({owner: req.params.id});
res.json(posts);
} catch(e) {
console.log(e);
res.status(500).json({message: "Ошибка сервера: " + e.message});
}
}
}
module.exports = Postscontroller;
Posts routes:
const router = require("express").Router();
const Postscontroller = require("../controllers/posts.controller");
router.get("/user/:id", authMiddleware, (req, res) => {
new Postscontroller().getUserPosts(req, res);
})
module.exports = router;