简体   繁体   中英

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. 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. What does your console.log(replyContent) print out? 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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM