我正在尝试在discussionReplyingSchema中保存一些数据,而不是将它连接到讨论模式。这是我讨论和回复的两个原理图:
const mongoose = require('mongoose');
const ObjectID = mongoose.Schema.Types.ObjectId;
let discussionSchema = mongoose.Schema({
title: {type: String, required: true},
content: {type: String},
author: {type: ObjectID, required: true, ref: 'User'},
date: {type: Date, default: Date.now()},
reply: [{ type: ObjectID, ref: 'Replying' }]
});
let discussionReplyingSchema = mongoose.Schema({
content: {type: String, required: true},
author: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},
date: {type: Date, default: Date.now()}
});
const Discussion = mongoose.model('Discussion', discussionSchema);
const Replying = mongoose.model('Replying', discussionReplyingSchema);
module.exports = Discussion;
module.exports = Replying;
在控制器中我获取用户和内容并尝试将它们保存在猫鼬中但我收到错误。代码:
replyPost: (req, res) => {
let replyParts = req.body;
let replyContent = req.body.replyContent;
console.log(replyContent);
let userId = req.user.id;
replyParts.author = userId;
Replying.create(replyParts).then(reply => {
req.user.reply.push(reply.id);
req.user.save(err => {
if (err) {
res.render('/');
} else{
res.redirect('/');
}
});
});
}
现在数据库就是这样的:
“回复”:[],
我正在为我的项目做这个,所以如果有可能,有人可以向我解释哪里有bug并在可能的情况下修复它?
答案 0 :(得分:0)
看起来你可能想要使用replyContent和replyParts保存,但我不确定。你的console.log(replyContent)打印出来了什么?此外,在您的承诺中添加一个catch,以便您可以捕获错误并查看发生了什么,它可能只是架构差异。
replyPost: (req, res) => {
let replyParts = req.body;
console.log('replyParts', replyParts);
let replyContent = req.body.replyContent;
console.log('replyContent', replyContent);
let userId = req.user.id;
replyParts.author = userId;
Replying.create(replyParts).then(reply => {
req.user.reply.push(reply.id);
req.user.save(err => {
if (err) {
console.log('USER SAVE ERR:' + err);
res.render('/');
} else{
res.redirect('/');
}
});
}).catch(err => console.log('REPLYING ERR:' + err));
}