我正在创建一个社交媒体应用,例如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)
能否请您指出我的错误所在或帮助我找到更好的方法。 如果您能帮助我,我将非常感谢!
答案 0 :(得分:1)
我在Github上创建了一个最小的仓库,以演示如何以您所需的方式使用填充的有效示例。
我在README.md中为您概述了许多内容,解释了可能的改进以及问题所在。
我有义务说,我是一名业余爱好者开发人员,因此请轻视我的意见/工作(可能与专业工程师不同),尽管这足以使您入门!
作为奖励,我提供了一个控制器->服务->模型设计模式的示例,该模式着重于分离表示,业务逻辑和数据访问。
尽管我个人建议至少研究一下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(),
});
},
};