如何通过ID与mongoose一起选择mongo子文档? [英] How to select a mongo subdocument by id with mongoose?

查看:82
本文介绍了如何通过ID与mongoose一起选择mongo子文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读一本书,代码不起作用.谷歌和这里的一切都表明该代码是正确的!它不起作用

I'm going through a book and the code doesn't work. Everything in google and here indicated that the code is right! It doesn't work

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()不返回任何内容.

The id is not a function, so id() returns nothing.

我尝试对ID号进行硬编码,使我在网上发现的很多东西变得很累,但最重要的是location.reviews.id只是一个值.我也做了Loc.findById(req.params.locationid).reviews ...:wherefindById,什么也没有!我也花了很多时间尝试_id以及与此相关的许多事情

I tried hard coding the id number, tired many things that I found online, but the bottom line is that location.reviews.id is just a value. I also did Loc.findById(req.params.locationid).reviews ...: where, findById, nothing! I also waisted a lot of time trying _id and many things that went with that

如果reviews.id匹配,我可以浏览所有评论并停止,但是我想知道作者正在尝试做什么.

I could loop through the reviews and stop if the reviews.id match, but I want to know what the author was trying to do.

据我了解,location是一个javascript对象,自然不能使用id作为功能

The way I understand it is that location is a javascript object, it's natural not to be able to use the id as a function

这是架构

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]
});


整个模块代码是(我会共享它,以防万一我没有选择正确的块):


The entire module code is (I though I'd share it incase I didn't select the right chunk):

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"
    });
  }
};

比你有帮助吗?

推荐答案

在我们的讨论中,我们找到了

Per our discussion, we found the root cause by

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

id: ObjectId()将在子文档中创建id字段,而在reviews子文档中创建_id字段.

id: ObjectId() will create id field in the subdocument and without _id field in the reviews subdocument.

id() 方法用于documentArray具有用于查找的特殊id方法文档的_id.由于reviews文档数组中没有_id字段,因此无法正常工作.

id() method is used to documentArrays have a special id method for looking up a document by its _id. Since there is no _id field in reviews document array, it does not work well.

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

这篇关于如何通过ID与mongoose一起选择mongo子文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆