使用Node.js将嵌套文档保存在猫鼬中时的错误处理

时间:2019-02-21 08:15:02

标签: node.js mongoose logic

我有两个模式,用户和答复。我提到了用户的回复。问题是我必须创建一个回复,然后将其推送到用户的回复数组。如果创建了回复但由于任何问题找不到用户该怎么办!?答复悬挂在空中,而没有附加到任何用户。有什么解决方法吗?

回复架构:

const mongoose = require('mongoose');

const requestReplySchema = mongoose.Schema({
    email: String,
    answers: [
        {
            number: Number,
            title: String,
        }
    ]
}, {timestamps: true});

module.exports = mongoose.model('RequestReply', requestReplySchema);

用户架构(简化版):

const mongoose = require('mongoose');
const passportLocal = require('passport-local-mongoose');

const userSchema = mongoose.Schema({
    firstName: String,
    lastName: String,
    email: String,
    requestReplies: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'RequestReply'
        }
    ]
}, {timestamps: true});

module.exports = mongoose.model('User', userSchema);

此部分的NodeJS代码:

let postReply = (req, res)=>{

    let replyAnswers = [];

    if(req.body.answers && (req.body.answers).length > 0){
        replyAnswers = req.body.answers;
    } else {
        return res.json({status: false, message: 'answers not properly formed'});
    }

    const newReply = {
        email: req.email,
        answers: replyAnswers,
    };

    RequestReply.create(newReply, (error, createdReply)=>{
        if(error || createdReply === null){
            return res.status(400).json({status: false, message: 'error getting data'})
        }

        User.findOne({email: req.email}, (error, foundUser)=>{
           if(error || foundUser === null){
               // what can I do here!? the request is saved, 
               // but the user is not found or and error happened
           }
        });
        return res.json({status: true})
    });
};

2 个答案:

答案 0 :(得分:2)

如果没有用户就无法存在回复,则首先必须找到该用户。如果不存在,则抛出错误;如果存在,则只需创建Reply,然后将其附加到找到的用户即可。

User.findOne({email: req.email}, (error, foundUser)=>{
    if(error || foundUser === null){
        return res.status(400).json({status: false, message: 'user not found, or   whatever'})
    }
    RequestReply.create(newReply, (error, createdReply)=>{
        if(error || createdReply === null){
            return res.status(400).json({status: false, message: 'error getting data'})
        }
        // TODO Update user with the new reply  
    }
});

无论如何,使用Mongoose,您可以使用promise并摆脱那些回调,嵌套语句,我认为这更干净。

答案 1 :(得分:1)

如果您使用副本集,则可以设置事务(https://mongoosejs.com/docs/transactions.html)。 否则,我将尝试扭转逻辑:我将检索用户,然后保存RequestReply。创建RequestReply之后,我将使用创建的对象的_id更新用户。