node.js - 如何使用 mongoose 通过 id 选择 mongo 子文档?

标签 node.js mongodb mongoose

我正在阅读一本书,但代码不起作用。谷歌和这里的所有内容都表明代码是正确的!不起作用

Loc
      .findById(req.params.locationid)
      .select('name reviews')
      .exec(
        function(err, location) {
          if (location.reviews && location.reviews.length > 0) {
            // this is the problem:
            review = location.reviews.id(req.params.reviewid); 
            if (!review) {
              sendJSONresponse(res, 404, {
                "message": "reviewid not found"
              });
            } else {
              response = {
                location: {
                  name: location.name,
                  id: req.params.locationid
                },
                review: review
              };
              sendJSONresponse(res, 200, response);
            }
          }
        }
    );

id 不是函数,因此 id() 不返回任何内容。

我尝试对 id 号进行硬编码,厌倦了我在网上找到的许多东西,但最重要的是 location.reviews.id 只是一个值。我还做了 Loc.findById(req.params.locationid).reviews ...: where, findById,什么也没有!我还花了很多时间尝试 _id 以及随之而来的许多事情

我可以循环浏览评论,并在 reviews.id 匹配时停止,但我想知道作者想要做什么。

我的理解是,location是一个javascript对象,自然不能将id用作函数

这是架构

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

var locationSchema = new mongoose.Schema({ 
    name: {type: String, required: true},
  address: String,
  rating: {type: Number, "default": 0, min: 0, max: 5},
  facilities: [String],
  coords: {type: [Number], index: '2dsphere'},
  openingTimes: [openingTimeSchema], //nesting a schema
  reviews: [reviewSchema]
});
<小时/>

整个模块代码是(我想分享它,以防我没有选择正确的 block ):

module.exports.reviewsReadOne = function(req, res) {
  console.log("Getting single review");
  if (req.params && req.params.locationid && req.params.reviewid) {
    Loc
      .findById(req.params.locationid)
      .select('name reviews')
      .exec(
        function(err, location) {
          if (location.reviews && location.reviews.length > 0) {
            review = location.reviews.id(req.params.reviewid);
            if (!review) {
              sendJSONresponse(res, 404, {
                "message": "reviewid not found"
              });
            } else {
              response = {
                location: {
                  name: location.name,
                  id: req.params.locationid
                },
                review: review
              };
              sendJSONresponse(res, 200, response);
            }
          }
        }
    );
  } else {
    sendJSONresponse(res, 404, {
      "message": "Not found, locationid and reviewid are both required"
    });
  }
};

你帮忙吗?

最佳答案

根据我们的讨论,我们找到了根本原因

db.locations.update({ name: 'Starcups' }, 
                    { $push: { 
                         reviews: { 
                            author: 'Simon Holmes', 
                            id: ObjectId(), // issue is here
                            rating: 5, ... } } })

id: ObjectId() 将在子文档中创建 id 字段,并且在 reviews 中不创建 _id 字段子文档。

id()方法用于 documentArrays 有一个特殊的 id 方法,用于通过其 _id 查找文档。由于 reviews 文档数组中没有 _id 字段,因此它无法正常工作。

请从您的代码中删除 id: ObjectId()

关于node.js - 如何使用 mongoose 通过 id 选择 mongo 子文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35677141/

相关文章:

node.js - DynamoDB 应用程序架构

node.js - package-lock.json 也应该发布吗?

javascript - "loose": true is not fixing Support for the experimental syntax 'classProperties' isn't currently enabled

ruby - find_one MongoDB Ruby 驱动程序

node.js - 将整个原始文档置于新的属性名称下

javascript - 为什么我在应用程序中使用 mongoose 时无法检索任何结果

node.js - 我怎么知道mongodb是否是由mongoose启动的?

javascript - Node.js:读取 URL 中传递的参数

node.js - NodeJS 无法连接到服务器 ECONNREFUSED 上的 MongoDB

node.js - Nodejs : Can't set headers after they are sent