是我的第一个问题。我的问题是我想从对象Customer中的Contacts:{type:[contactSchema]数组中获取一个带有_id的对象contact,但我得到的是hole对象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我会得到空。
null
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);
}
)
})
由于您正在查询客户,因此您的查询将返回一个Customer对象。此外,使用投影,您可以隐藏查询返回的对象的属性。在此基础上,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);
}
)