node.js - 使用nodejs在mongoose中保存嵌套文档时的错误处理

标签 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})
    });
};

最佳答案

如果没有用户就无法存在回复,那么首先您必须找到该用户。如果不存在,则抛出错误,如果存在,则创建 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 并摆脱那些回调、嵌套句子,我认为它更干净。

关于node.js - 使用nodejs在mongoose中保存嵌套文档时的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54802208/

相关文章:

javascript - 如何使用 Puppeteer 选择具有同一类的所有子 div?

javascript - Mongoose 文档过滤属性

php - 编程逻辑最佳实践——冗余检查

prolog - 在这种情况下,当 gprolog 显示 "true?"而不是 "yes"时,这意味着什么?

javascript - nodejs 流可读卡在第一个可读对象

node.js - 在 NodeJS 应用程序中分离 socket.io 相关代码的最佳实践是什么?

node.js - MongoDB将相关的收集项目计数与其他收集结果合并

javascript - Mongoose 填充的Where子句

c++ - 如何使用C++中的插槽图/对象池模式管理数百万个游戏对象?

javascript - 如何等待建立数据库连接并为数组中的每个数据库执行查询