gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:58:04 24 4
gpt4 key购买 nike

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

回复架构:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com