mongodb保存在嵌套对象(node.js)应用程序中

时间:2017-03-30 17:07:43

标签: javascript node.js mongodb

我从代码中找到“bookid not found”。 我可以使用邮递员分别添加作者和标题,但我似乎无法让reviewsCreate函数工作,我错过了什么? PLS帮助

我的架构

    var mongoose = require('mongoose');

    var reviewSchema = new mongoose.Schema({
        author: {
            type: String,
            required: true
        },
        rating: {
            type: Number,
            required: true,
            min: 0,
            max: 5
        },
        reviewText: { type: String, required: true },
        createdOn: {
            type: Date,
            "default": Date.now
        }
    });

    var titleSchema = new mongoose.Schema({
        title: {
            type: String,
            required: true
        },
        favouredBy: {
            type:[String],
            required: false
        },
        reviews: [reviewSchema]

    });
    var bookSchema = new mongoose.Schema({
        bookAuthor: {
            type: String,
            required: true
        },
        titles: [titleSchema]
    });
    mongoose.model('Book', bookSchema);
   router.post('/books/:bookid/titles/:titleid/reviews',ctrlReviews.reviewsCreate);
    module.exports.reviewsCreate = function(req, res) {
        if (req.params.bookid) {
            Bok
                .findById(req.params.titleid)
                .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) {
        if (!book) {
            sendJSONresponse(res, 404, "bookid not found");
        } else {
            book.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 {
                    updateAverageRating(book._id);
                    thisReview = book.reviews[book.reviews.length - 1];
                    sendJSONresponse(res, 201, thisReview);
                }
            });
        }
    };

这是我使用你的建议时得到的 错误:

  

TypeError:无法读取未定义

的属性'push'

当我把console.log(书);在doAddrivew函数下面。

    { _id: 58dd21c3cb77090b930b6063,
      titles:
       [ { title: 'this is title',
           _id: 58dd3f2701cc081056135dae,
           reviews: [],
           favouredBy: [Object] },
         { title: 'this is the second tittle',
           _id: 58dd42a59f12f110d1756f08,
           reviews: [],
           favouredBy: [Object] } ] 
    }

1 个答案:

答案 0 :(得分:3)

您的图书架构具有titles属性,该属性还具有reviews

var doAddReview = function(req, res, book, author) {
    if (!book) {
        sendJSONresponse(res, 404, "bookid not found");
    } else {
       /* book.titles.reviews.push({  
            author: author,
            rating: req.query.rating,
            reviewText: req.query.reviewText
        }); */
        book.titles[0].reviews.push({ // to push in first element
            author: author,
            rating: req.query.rating,
            reviewText: req.query.reviewText
        });
        book.save(function(err, book) {
            var thisReview;
            if (err) {
                sendJSONresponse(res, 400, err);
            } else {
                updateAverageRating(book._id);
                // -----------------------------
                thisReview = book.reviews[book.reviews.length - 1];
               // thisReview = book.titles.reviews[book.titles.reviews.length - 1];
                // here also you may have to modify
                sendJSONresponse(res, 201, thisReview);
            }
        });
    }
}

更新

  1. 首先,book应该是Book模型的实例。
  2. titles中定义的bookSchema属性是一个数组,所以当你想在bookSchema中添加数据时,bookAuthor属性只有一个字符串,但是titles字段会包含[{}, {}, {}]之类的对象,因此您必须选择titles的索引,例如titles[0]titles[1],然后按下title你要评论
  3. 注意:由于reviews的{​​{1}}也是一个数组,您使用索引并从该数组中选择所需的元素,以执行像[reviewSchema]这样的更新,删除等操作>

    假设我想要推入book.titles[0].reviews[1]数组第一个元素

    titles
    book.titles[0].reviews.push({
        author: author,
        rating: req.query.rating,
        reviewText: req.query.reviewText
    });
    

    在这里,您必须选择要推送的 { _id: 58dd21c3cb77090b930b6063, titles: [ { title: 'this is title', _id: 58dd3f2701cc081056135dae, reviews: [], favouredBy: [Object] }, { title: 'this is the second tittle', _id: 58dd42a59f12f110d1756f08, reviews: [], favouredBy: [Object] } ] } 内有2个对象,

    如果您想在titles的第一个对象中推送评论,请选择_id: 58dd3f2701cc081056135dae,

    titles[0]_id: 58dd42a59f12f110d1756f08

    由于您的数组将包含多个对象,因此您必须匹配要执行titles[1]操作的对象,因此要过滤文档,您可以使用update位置操作

    https://docs.mongodb.com/v3.2/reference/operator/update/position/

    请看一下点符号 https://docs.mongodb.com/manual/core/document/#dot-notation