[英]I get error when I try to save in mongoose?
I am trying to save some data in discussionReplyingSchema and than connect it to the discussion Schema. 我正在尝试将一些数据保存在DiscussionReplyingSchema中,然后将其连接到讨论模式。 Those are my two schematics for discussions and replies:
这些是我的两个示意图,用于讨论和回复:
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;
In the controller I get the user and content and trying to save them in mongoose but I get error. 在控制器中,我得到了用户和内容,并试图将它们保存在猫鼬中,但出现错误。 Code:
码:
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('/');
}
});
});
}
That's how the database is right now: 现在数据库就是这样的:
"reply": [], “回复”:[],
I am doing it for my project so if possible can someone explain to me where is the bug and fix it if possible? 我正在为我的项目这样做,所以如果可能的话,有人可以向我解释错误在哪里,并在可能的情况下修复它?
it looks like you may be wanting to save with replyContent vs replyParts but I'm not sure. 看来您可能想要保存与replyContent和replyParts一起使用,但我不确定。 What does your console.log(replyContent) print out?
您的console.log(replyContent)打印什么? Also, add a catch to your promise so you can trap the error and see what is going on, it's likely just a schema discrepancy.
另外,在您的承诺中添加一个陷阱,以便您可以捕获错误并查看发生了什么,这很可能只是架构差异。
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.