Estoy tratando de construir un blog simple con un sistema de comentarios con mongoose y express. No hay problema en crear y publicar blogs aquí y cada publicación se puede mostrar correctamente. Sin embargo, hay algunos problemas asociados con los comentarios y cada blog. La relación entre los comentarios y la publicación del blog se estableció aplicando mongoose.Schema.Types.ObjectId en el esquema de publicación y los comentarios se crearon para almacenar una matriz de ID de comentarios. Creo que las estructuras del esquema son correctas y puede haber algunos problemas en mi código para el enrutamiento. Por favor, ayuda, gracias.
// Post Schema const mongoose = require('mongoose'); const postSchema = new mongoose.Schema({ title: { type: String, trim: true, required: true }, text: { type: String, trim: true, required: true }, date: { type: Date, default: Date.now }, comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }] }) postSchema.virtual('url').get(function(){ return '/post/' + this._id }) module.exports = mongoose.model('Post', postSchema); // Comment Schema const mongoose = require('mongoose'); const commentSchema = new mongoose.Schema({ text: { type: String, trim: true, required: true }, date: { type: Date, default: Date.now } }) module.exports = mongoose.model('Comment', commentSchema); // Router const express = require('express'); const Post = require('../models/post'); const Comment = require('../models/comment'); const router = new express.Router(); // Get comments router.get('/post/:id/comment', (req, res) => { res.render('post-comment', {title: 'Post a comment'}) }) // Create and Post comments, this is where I think I made mistakes router.post('/post/:id/comment', async (req, res) => { const comment = new Comment({text: req.body.text}); const post = await Post.findById(req.params.id); const savedPost = post.comments.push(comment); savedPost.save(function(err, results){ if(err) {console.log(err)} res.render('post_details', {title: 'Post details', comments: results.comments}) } ) }) // Get each post details. // Trying to display comments, but it is all empty and I realized // the comments array is empty, I can see the comments create in // mongodb database why is that????? router.get('/post/:id', (req, res) => { Post.findById(req.params.id) .populate('comments') .exec(function(err, results) { if(err) {console.log(err)} res.render('post_details', {title: 'Post details', post: results, comments: results.comments}) }) }) router.get('/new', (req, res) => { res.render('create-post', {title: 'Create a post'}) }) router.post('/new', (req, res) => { const post = new Post({ title: req.body.title, text: req.body.text }); post.save(function(err) { if(err) {console.log(err)} res.redirect('/') }) }) router.get('/', (req, res) => { Post.find() .exec(function(err, results) { if(err) {console.log(err)} res.render('posts', {title: 'All Posts', posts: results}) }) }); module.exports = router;