我如何在嵌套的mongodb上推送文档

时间:2017-03-30 21:51:24

标签: mongodb

如果我想在第一个标题中添加评论,作者,评分和评论文字,我该怎么做。

    {
        "_id": ObjectId("58dd21c3cb77090b930b6063"),
        "bookAuthor": "wwww",
        "titles": [{
            "title": "this is title",
            "_id": ObjectId("58dd3f2701cc081056135dae"),
            "reviews": [],
            "favouredBy": [
                "bb, aa, cc"
            ]
        }, {
            "title": "this is the second tittle",
            "_id": ObjectId("58dd42a59f12f110d1756f08"),
            "reviews": [],
            "favouredBy": [
                "all"
            ]
        }],
        "__v": 0
    }

来自应用程序,这是我尝试但继续得到“TypeError:无法读取属性'推送'未定义”错误

    module.exports.reviewsCreate = function(req, res) {
        if (req.params.bookid) {
            Bok
                .findById(req.params.bookid)
                .select('titles')
                .exec(
                    function(err, book) {
                        if (err) {
                            sendJSONresponse(res, 400, err);
                        } else {
                            doAddReview(req, res, book);
                        }
                    }
                );
        } else {
            sendJSONresponse(res, 404, {
                "message": "Not found, bookid required"
            });
        }

    };

    var doAddReview = function(req, res, book, author) {
        console.log(book);
        if (!book) {
            sendJSONresponse(res, 404, "bookid not found");
        } else {
            book.titles.reviews.push({
                author: author,
                rating: req.query.rating,
                reviewText: req.query.reviewText

            });
            book.save(function(err, book) {
                var thisReview;
                if (err) {
                    sendJSONresponse(res, 400, err);
                } else {
                    sendJSONresponse(res, 201, book);
                }
            });
        }
    };

0 个答案:

没有答案