如何使路线同步

时间:2019-01-18 11:47:24

标签: node.js mongodb express mongoose async-await

我有一条评论的路线,我想获取特定案卷号的所有评论。同样,对于每个注释,可能有多个文件。我想以同步方式获取所有内容,而默认情况下,使用nodeJS时,其工作是以异步方式进行的。注释和文件都存储在不同的集合中。

这是我要将结果作为单个JS对象返回的路线

router.get("/history/:docket_no", (req, res) => {
    Comments.find({ docket_no: req.params.docket_no })
    .exec()
    .then(comments => {
        var cmnts = [];
        if (comments.length >= 1) {
            for(var i = 0; i < comments.length; i++) {
                var cmntImgs = [];
                CommentImage.find({ comment_id: comments[i]._id })
                .exec()
                .then(commentImages => {
                    for(var j = 0; j < commentImages.length; j++) {
                        var filePath = commentImages[j].comment_image;
                        var fileName = filePath.split("\\");
                        cmntImgs[j] = {
                            filesName: fileName[fileName.length-1],
                            filePath: filePath
                        };
                    }
                    console.log('Images',cmntImgs);
                })
                .catch(err => {
                    console.error(err);
                });

                cmnts[i] = {
                    id: comments[i]._id,
                    user_name: comments[i].user_name,
                    role_id: comments[i].role_id,
                    message: comments[i].message,
                    create_date: comments[i].create_date,
                    files: cmntImgs
                };
            };

            return res.status(200).json({
                comments: cmnts
            });

        } else {
            return res.status(400).json({
                msg: "No comments found"
            });
        }
    })
    .catch(err => {
        console.error(err);
        res.send(500).json({
          msg: "Error"
        });
    });
});

这是评论模式...

const mongoose = require("mongoose");

//Comments Schema
const CommentsSchema = mongoose.Schema({
    docket_no: {
        type: String,
        trim: true,
        required: true
    },
    user_name: {
        type: String,
        required: true
    },
    role_id: {
        type: Number,
        required: true
    },
    message: {
        type: String,
        trim: true,
        required: true
    },
    create_date: {
        type: Date,
        default: Date.now,
        required: true
    }
});

module.exports = mongoose.model("Comments", CommentsSchema);

这是文件架构...

const mongoose = require("mongoose");

//CommentImage Schema
const CommentImage = mongoose.Schema({
    docket_no: {
        type: String,
        trim: true,
        required: true
    },
    comment_id: {
        type: String,
        trim: true,
        required: true
    },
    comment_image: {
        type: String,
        trim: true,
        required: true
    }
});

module.exports = mongoose.model("CommentImage", CommentImage);

这是当前输出-

{
    "comments": [
        {
            "id": "5c3efdf77ad5e5176cc65bc4",
            "user_name": "aaa",
            "role_id": 1,
            "message": "comment test 1",
            "create_date": "2019-01-16T09:48:39.023Z",
            "files": []
        },
        {
            "id": "5c40311bdad6ad1084d24b9c",
            "user_name": "aaa",
            "role_id": 1,
            "message": "comment test 1",
            "create_date": "2019-01-17T07:39:07.081Z",
            "files": []
        }
    ]
}

所需的输出-

{
    "comments": [
        {
            "id": "5c3efdf77ad5e5176cc65bc4",
            "user_name": "aaa",
            "role_id": 1,
            "message": "comment test 1",
            "create_date": "2019-01-16T09:48:39.023Z",
            "files": []
        },
        {
            "id": "5c40311bdad6ad1084d24b9c",
            "user_name": "aaa",
            "role_id": 1,
            "message": "comment test 1",
            "create_date": "2019-01-17T07:39:07.081Z",
            "files": [
                        {
                            filesName: '1547710746976-FD Direct Screen #2.jpg',
                            filePath: 'uploads\\1547710746976-FD Direct Screen #2.jpg' },
                        {
                            filesName: '1547710746987-New Doc 2018-05-31.doc',
                            filePath: 'uploads\\1547710746987-New Doc 2018-05-31.doc' },
                        {
                            filesName: '1547710747024-New Doc 2018-05-31.docx',
                            filePath: 'uploads\\1547710747024-New Doc 2018-05-31.docx' },
                        {
                            filesName: '1547710747053-New Doc 2018-05-31.pdf',
                            filePath: 'uploads\\1547710747053-New Doc 2018-05-31.pdf' }
                    ]
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

猫鼬不支持同步操作。您需要将路由处理程序转换为async函数,以利用await的优势。这使它看起来/看起来像是同步的。

错误处理应委托Express'error middleware

router.get("/history/:docket_no", async (req, res) => {
    const { docket_no } = req.params
    const comments = await Comments.find({ docket_no }).exec()

    if (comments.length < 1) {
        res.status(400).json({ msg: "No comments found."})
        return
    }

    const mappedComments = []
    const mappedImages = []

    for(let i = 0; i < comments.length; i++) {
        const images = await CommentImages
            .find({ comment_id: comments[i]._id })
            .exec()

        for(let j = 0; j < images.length; j++) {
            const filePath = images[j].comment_image
            const fileName = filePath.split("\\")
            mappedImages[j] = {
                filesName: fileName[fileName.length - 1],
                filePath
            }
        }

        console.log(`Images ${mappedImages}`)

        const {
            _id,
            user_name,
            role_id,
            message,
            create_date
        } = comments[i]

        mappedComments[i] = {
            id: _id,
            user_name,
            role_id,
            message,
            create_date,
            files: mappedImages
        }
    }

    res.json({ comments: mappedComments })
})

上面的示例还利用了shorthand property namesobject destructuring