【问题标题】:Problem with. Post. Comment Schemas - Mongoose/Typescript有问题。邮政。评论模式 - Mongoose/Typescript
【发布时间】:2020-05-09 11:24:10
【问题描述】:

我正在创建一个社交媒体应用,比如 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 的文件(Commentario.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/commentario.js:21:26 在 Layer.handle [as 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)

能否请您指出我的错误在哪里或帮助我找到更好的方法。 如果您能帮助我,我将不胜感激!

【问题讨论】:

    标签: node.js typescript mongoose-schema mongoose-populate


    【解决方案1】:

    我在 Github 上创建了一个最小的 repo 来演示一个以您需要的方式使用填充的工作示例。

    我在 README.md 中专门为您概述了许多内容,解释了可能的改进以及问题所在。

    我有义务说,我是一名业余开发者,所以请轻视我的意见/工作(可能与专业工程师不同),尽管这应该足以让您入门!

    作为奖励,我包含了一个 Controller->Service->Model 设计模式的示例,因为它专注于解耦表示、业务逻辑和数据访问。

    我尽量避免实现任何类以保持简单,尽管我个人建议至少研究 OOP 范式。

    https://github.com/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(),
        });
      },
    };
    

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 2011-01-16
      • 2017-02-21
      • 2011-09-28
      • 2012-12-05
      • 2012-11-26
      • 2020-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多