[英]I get error when I try to save in mongoose?
我正在嘗試將一些數據保存在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('/');
}
});
});
}
現在數據庫就是這樣的:
“回復”:[],
我正在為我的項目這樣做,所以如果可能的話,有人可以向我解釋錯誤在哪里,並在可能的情況下修復它?
看來您可能想要保存與replyContent和replyParts一起使用,但我不確定。 您的console.log(replyContent)打印什么? 另外,在您的承諾中添加一個陷阱,以便您可以捕獲錯誤並查看發生了什么,這很可能只是架構差異。
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.