Mongoose get Object 取出一个对象

Mongoose get Object out an Object

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

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 我会得到 null。

由于您正在查询 Customers,因此您的查询将 return 一个 Customer 对象。但是,使用 projections, you can hide properties of the object returned by the query. On top of that, 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);
  }
) 

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