【问题标题】:Mongoose nested query猫鼬嵌套查询
【发布时间】:2021-03-23 19:33:35
【问题描述】:

联系人模型有一个用户 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"
    }

如何通过模型查找方法获得此联系?

【问题讨论】:

标签: node.js express mongoose postman


【解决方案1】:
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 匹配的用户详细信息,这正是您想要的。

【讨论】:

    猜你喜欢
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2019-04-06
    • 2015-04-10
    • 1970-01-01
    相关资源
    最近更新 更多