最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

问题。发布。注释模式

网站源码admin15浏览0评论

问题。发布。注释模式

问题。发布。注释模式

我正在创建社交媒体应用,例如instagram。老实说,这是我第一次使用非关系数据库,因此我的逻辑存在一些问题。我不明白如何保存创建架构之间关系的ID。我对用户没有问题-发布。但我在发布帖子时遇到了一些错误-评论我保留了部分代码,以便您可以理解我的问题。这是我的发布架构

    const postSchema = new Schema({
        created: {
            type: Date
        },
        descripcion:{
            type: String,
            required: [true, 'Cada prenda debe ser descrita']
        },
        img: [{
            type: String
        }],
        user: {
            type: Schema.Types.ObjectId,
            ref: 'Usuario',
            required: [true, 'Debe existir una referencia a un usuario']
        }, 
        comment: [{
            type: Schema.Types.ObjectId,
            ref: 'Comentario'
         }]
    });
    interface IPost extends Document{
        created: Date;
        descripcion: string;
        img: string[];
        cords: string;
        user: string;
        comment: string;
}

这是我的评论架构:

const comentarioSchema = new Schema({
    created: {
        type: Date
    },
    autor: {
        type: Schema.Types.ObjectId,
        ref: 'Usuario',
        required: [true, 'Debe existir una referencia a un usuario']
    },
    contenido: {
        type:  String,
        required: [true, 'No se aceptan comentarios vacios']
    },
    post:{
      type: Schema.Types.ObjectId,
      ref: 'Post',
      required: [true, 'Debe existir una referencia al post al que este comentario pertenece']
    }
});
interface IComentario extends Document{
    created: Date;
    autor: string;
    contenido: string;
    post: string;
}

最后,这就是问题所在。我有一个名为Comment.ts的文件(Comentario.ts-用我的母语):

import { Router, Response } from "express";
import { verificaToken } from '../middlewares/autenticacion';
import { Comentario } from '../models/comentario.model';
const comentarioRoutes = Router();

comentarioRoutes.post('/',[verificaToken], (req:any, res: Response)=> {

    const body = req.body;
    body.autor = req.usuario._id;
    body.post = req.post._id;

    Comentario.create(body).then( async comentarioDB => {

        await comentarioDB.populate('usuario','-password').populate('post').execPopulate();

        res.json({
            ok:true,
            comentario: comentarioDB
        });
    }).catch(err=> {
        res.json(err)
    });



});

export default comentarioRoutes;

我如何使用请求尝试使用填充来自动存储帖子的ID,但出现此错误:

TypeError:无法读取未定义的属性'_id'在/Users/mari/Desktop/Projects/ionic/fotos-server/dist/routes/comentario.js:21:26在Layer.handle [作为handle_request](/Users/mari/Desktop/Projects/ionic/fotos-server/node_modules/express/lib/router/layer.js:95:5)在下一个(/Users/mari/Desktop/Projects/ionic/fotos-server/node_modules/express/lib/router/route.js:137:13)在/Users/mari/Desktop/Projects/ionic/fotos-server/dist/middlewares/autenticacion.js:12:9在processTicksAndRejections(internal / process / task_queues.js:97:5)

[能否请您指出我的错误所在或帮助我找到更好的方法。如果您能帮助我,我将非常感谢!

回答如下:

[我在Github上创建了一个最小的仓库,以演示按照您要求的方式使用填充的有效示例。

我在README.md中为您概述了很多事情,解释了可能的改进以及问题所在。

[我有义务说,我是一个业余爱好者开发人员,因此,请轻视我的意见/工作(可能与专业工程师不同,尽管这足以使您入门!

此外,我还提供了一个Controller-> Service-> Model设计模式的示例,因为它专注于分离表示,业务逻辑和数据访问。

尽管我个人建议至少考虑一下OOP范例,但我尝试避免实现任何类以使事情保持简单。

[https://github/Isolated-/mari-working-mongoose-随时让我知道是否可以提供进一步的帮助和好运!

对于遇到类似问题而在此答案中绊脚石的任何人,工作代码将类似于:

export const commentController = {
  post: async (req: Request, res: Response) => {
    const body = req.body;
    const { postId, authorId, commentText } = body;

    // implement real validation logic
    if (!postId || !authorId || !commentText) {
      return res.status(400).json({
        error: 'Bad Request',
      });
    }

    const comment = await new Comment({
      post: postId,
      author: authorId,
      content: commentText,
    }).save();

    return res.status(201).json({
      ok: true,
      comment: await comment.populate('author').populate('post').execPopulate(),
    });
  },
};

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论