【问题标题】:Mongoose get Object out an ObjectMongoose 将对象取出一个对象
【发布时间】:2021-06-21 04:46:12
【问题描述】:

是我在这里的第一个问题。 我的问题是我想从数组联系人中获取一个带有 _id 的对象联系人:{ type: [contactSchema] in an Object Customer。但我得到了洞对象客户。

router.route('/customers/:id/contact/:contacts_id').get((req, res) => {
    Customer.findOne({
            "_id": req.params.id,
            "contacts._id": req.params.contacts_id
        },
        (err, customer) => {
            if (err)
                console.log(err);
            else
                res.json(customer);
        }
    )
})

如果我使用 Contact.findOne,我会得到空值。

【问题讨论】:

    标签: javascript node.js mongodb mongoose backend


    【解决方案1】:

    由于您正在查询客户,因此您的查询将返回一个客户对象。然而,使用projections,您可以隐藏查询返回的对象的属性。最重要的是,elemmatch 可用于在数组中查找匹配项

    以下是在您的情况下如何使用它们:

    Customer.findOne(
      {_id: req.params.id},
      { projection: { _id: 0, contacts: { $elemMatch: { _id: req.params.contacts_id } } },
      (err, customer) => {
        if (err) console.log(err);
        else res.json(customer);
      }
    ) 
    

    【讨论】:

      【解决方案2】:

      router.route('/customers/:id/contact/:contacts_id').get((req, res) => {
          Customer.findOne({
                  "_id": mongoose.Types.ObjectId(req.params.id),
                  "contacts._id": mongoose.Types.ObjectId(req.params.contacts_id)
              },
              (err, customer) => {
                  if (err)
                      console.log(err);
                  else
                      res.json(customer);
              }
          )
      })

      【讨论】:

        猜你喜欢
        • 2018-12-16
        • 2019-04-08
        • 2018-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-31
        • 1970-01-01
        • 2014-10-29
        相关资源
        最近更新 更多