联系人模型具有用户ID和嵌套文档作为联系人
Contact.findOne({userId : req.userData.userId}).exec().then( doc =>{
console.log(doc);
res.status(200).json({doc})
}).catch(err => {
console.log(err);
res.status(500).json({error : err})
})
此代码输出是这样的:
{
"doc": {
"_id": "5fd4c77508f14a1e108c8788",
"userId": "5fd4c77508f14a1e108c8787",
"contacts": [
{
"_id": "5fd4e9cc08f14a1e108c8789",
"name": "muaz",
"number": 123415123,
"contactImage": "uploads\\2020-12-12T16-03-24.588Zqweqqq.png"
},
{
"_id": "5fd4ea102502ab1130549bbb",
"name": "muazs",
"number": 123415123,
"contactImage": "uploads\\2020-12-12T16-04-32.561Zqweqqq.png"
}]}
我从请求(req.params.userId)中获取联系人ID。
例如:当我收到请求时,req.param.userId = 5fd4e9cc08f14a1e108c8789
我想发送这样的响应:
{
"_id": "5fd4e9cc08f14a1e108c8789",
"name": "muaz",
"number": 123415123,
"contactImage": "uploads\\2020-12-12T16-03-24.588Zqweqqq.png"
}
如何找到模型查找方法的联系人?
const {userId}=req.params;
Contact.findOne({"contacts._id":userId}, {contacts:{$elemMatch:{_id:userId}})
.then(data=>res.send(data.contacts[0]))
.catch(err=>res.send("Not found!"))
这将只返回基于存储为_id的userId的匹配用户详细信息,正是您想要的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句