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

标签 javascript node.js mongodb

我从我的代码中得到“找不到 bookid”。 我可以使用 postman 分别添加作者和标题,但我似乎无法让 reviewsCreate 函数正常工作,我是不是遗漏了什么?请帮助

我的模式

    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: Cannot read property 'push' of undefined

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

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

最佳答案

您的图书架构具有 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. bookSchema中定义的titles属性是一个数组,所以当你想在bookSchema中添加数据时,bookAuthor 属性将只有一个字符串,但 titles 字段将包含像 [{}, {}, {}] 这样的对象,因此您必须选择索引titles,例如 titles[0]titles[1],然后推送到您要查看的 title

注意:[reviewSchema]reviews 也是一个数组,您可以使用索引并从该数组中选择所需的元素,以执行更新、删除等操作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] } ] 
    }

这里因为 titles 中有 2 个对象,所以您必须选择要推送的对象,

如果你想在 _id: 58dd3f2701cc081056135dae 的第一个对象中推送评论, 然后选择 titles[0]

对于 _id:58dd42a59f12f110d1756f08titles[1]

因为你的数组会有多个对象,所以你必须匹配你想要执行操作的对象,比如update,所以要过滤文档你可以使用 $ 位置运算符

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

请同时查看点符号 https://docs.mongodb.com/manual/core/document/#dot-notation

关于javascript - mongodb 保存在嵌套对象(node.js)应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43124216/

相关文章:

java - Websocket:页面重新加载后维护用户 session

javascript - 使用随机枢轴在 Javascript 中实现 QuickSort

javascript - 上传和编辑图片 node.js 服务器

javascript - Sequelize 使用 [Op.or] 查询父模型和包含的模型

node.js - Mocha 抛出超时,但 Mongoose 将数据保存到 Promise 链中的数据库?

javascript - 如何在 slickgrid 中拥有静态索引列

javascript - 动态地向可观察数组中的特定项目添加绑定(bind)(例如 hasfocus)

javascript - Express 项目中的嵌套路由

javascript - 如何使用 node-mongodb-native 连接到 Heroku?

MongoDB - "The dollar ($) prefixed field\' $$hashKey\' in\' 字段名".$$hashKey\' is not valid for storage.' "