【问题标题】:query to display subdocument not working查询显示子文档不起作用
【发布时间】:2017-06-10 17:03:38
【问题描述】:

我对 mongoose 还很陌生,我正在尝试编写一个查询,它只在我的主文档中返回一个子文档。

我的文档结构是这样的:

PROFILE
    - CONTACTS [ARRAY]

我编写了以下端点来返回一个联系人,其中我传递了个人资料 ID 和子文档的 ID:

"/:owerId/getcontact/:contactId"

我的 Express 函数代码如下所示:

router.route('/:ownerId/getcontact/:contactId')

    .get(function(req, res){
      Profile.findOne({'owner_id':req.params.ownerId}).then(function(err, profile){
        if(err)
          res.send(err);

        profile.findOne({'_id':req.params.contactId}).then(function(err, contact){
          if(err)
            res.send(err);
          res.json(contact);
        })

      })
    })

但此代码会返回整个配置文件。

当我尝试通过 ID 获取时,它会做同样的事情。这是我的代码,下面是返回的整个配置文件:

router.route('/:ownerId/getcontact/:contactId')

.get(function(req, res){
  Profile.findById(req.params.ownerId).then(function(err, profile){
    if(err)
      res.send(err);

      var data = profile.contacts.id(req.params.contactId);

    res.json(data);

  })
})





{
  "_id": "5886e3692ca4542c453431ee",
  "initial": "u",
  "last_name": "randal",
  "first_name": "chris",
  "owner_id": "5886e32c2ca4542c453431ed",
  "__v": 1,
  "contacts": [
    {
      "last_name": "Eltoro",
      "first_name": "Peter",
      "_id": "5886e3f5a219472cac886a9f",
      "businesses": [],
      "addresses": [],
      "phones": [
        {
          "phone_type": "mobile",
          "phone_number": "555-555-999",
          "_id": "5886e3f5a219472cac886aa2"
        },
        {
          "phone_type": "home",
          "phone_number": "999-876-000",
          "_id": "5886e3f5a219472cac886aa1"
        }
      ],
      "emails": [
        {
          "email_address": "tim@time.com",
          "_id": "5886e3f5a219472cac886aa0"
        }
      ]
    },
    {
      "college": "University of WA",
      "highschool": "Kalaheo",
      "birthday": "1990-12-22T08:00:00.000Z",
      "last_name": "Smith",
      "first_name": "Suzanne",
      "_id": "5886fb7fac288c2e31eabe0a",
      "businesses": [],
      "addresses": [
        {
          "zip": "98777",
          "state": "WA",
          "city": "Seattle",
          "address_2": "Apt 234",
          "address": "124 194th St. SW",
          "_id": "5886fb7fac288c2e31eabe0e"
        }
      ],
      "phones": [
        {
          "phone_type": "mobile",
          "phone_number": "206-899-9898",
          "_id": "5886fb7fac288c2e31eabe0d"
        },
        {
          "phone_type": "home",
          "phone_number": "206-789-0987",
          "_id": "5886fb7fac288c2e31eabe0c"
        }
      ],
      "emails": [
        {
          "email_type": "personal",
          "email_address": "suzanne@smith.com",
          "_id": "5886fb7fac288c2e31eabe0b"
        }
      ]
    },
    {
      "last_name": "Alabaster",
      "first_name": "Cindy",
      "_id": "5888b0bd3c025e54476828d9",
      "businesses": [],
      "addresses": [],
      "phones": [
        {
          "phone_type": "home",
          "phone_number": "999-999-0909",
          "_id": "5888b0bd3c025e54476828dc"
        },
        {
          "phone_type": "home",
          "phone_number": "000-000-0000",
          "_id": "5888b0bd3c025e54476828db"
        }
      ],
      "emails": [
        {
          "email_address": "Some@them.com",
          "_id": "5888b0bd3c025e54476828da"
        }
      ]
    }
  ],
  "businesses": [],
  "addresses": [],
  "phones": [
    {
      "phone_number": "999-999-9999",
      "phone_type": "mobile",
      "_id": "5886e37f2ca4542c453431ef"
    }
  ],
  "emails": []
}

【问题讨论】:

    标签: node.js mongodb express mongoose mongoose-schema


    【解决方案1】:

    Mongoose 子文档有特殊的方法来检索它们:

    router
      .route('/:ownerId/getcontact/:contactId')
        .get(function(req, res) {
          Profile.findOne({ owner_id: req.params.ownerId }, function(err, profile) {
            if ( err ) {
              res.send(err);
            }
            var contact = profile.contacts.id(req.params.contactId);
            res.json(contact);
          });
        });
    

    Mongoose Sub Documents

    【讨论】:

    • 这是因为您的个人资料_idowner_id 不同,所以您不应该使用findById,而应该使用findOne。答案已更新。
    • 我将 ownerId 参数更改为包含 _id。我只是没有更改参数名称。所以它实际上是通过_id查找配置文件。我已经尝试过 findOne 和 findById ,但由于某种原因,我仍然可以取回整个记录,而不仅仅是子文档。奇怪。
    • 检查你的路线,也许有一些路线覆盖了这条路线。
    【解决方案2】:

    另一条路线是通过聚合框架,您可以使用 $match$arrayElemAt$filter 运算符返回你想要的数据。

    考虑在您的 API 端点实现中运行以下聚合操作:

    router.route('/:ownerId/getcontact/:contactId')
        .get(function(req, res){
            var ownerId = mongoose.Schema.Types.ObjectId(req.params.ownerId),
                contactId = mongoose.Schema.Types.ObjectId(req.params.contactId);
    
            Profile.aggregate([
                { "$match": { "owner_id": ownerId } },
                {
                    "$project": {
                        "contact": {
                            "$arrayElemAt": [
                                { 
                                    "$filter": {
                                        "input": "$contacts",
                                        "as": "contact",
                                        "cond": { "$eq": ["$$contact._id", contactId] }
                                    }
                                },
                                0
                            ]
                        }
                    }
                }
            ]).exec(function(err, profile){
                if(err) res.send(err);          
                res.json(profile[0].contact);
            })
        })
    

    【讨论】:

      猜你喜欢
      • 2019-10-19
      • 2020-11-21
      • 2013-09-04
      • 1970-01-01
      • 2021-04-26
      • 2019-04-03
      • 1970-01-01
      • 2015-10-19
      • 2017-06-08
      相关资源
      最近更新 更多