【问题标题】:To search for document and then search for array element inside those document in mongoDB?要搜索文档,然后在 mongoDB 中的这些文档中搜索数组元素?
【发布时间】:2018-03-16 16:58:15
【问题描述】:

我一直在尝试为我的网站设置支持和反对的功能。这是我的架构

{
"_id" : ObjectId("5aa639cb4add7a1c58507ac1"),
"vote" : -7,
"votedBy" : [],
"Fbid" : "109590486545309",
"imageId" : "86i1dr8apv",
"email" : "emnnevbjyo_1520686942@tfbnw.net",
"event" : "selfie",
"__v" : 0}

现在,我正在尝试使用 imageId 查找我的文档,然后在 votedBy 数组中查找特定选民。如果具有某个值的查询结果根据赞成或反对的逻辑行事。这是我的赞成和反对代码

app.get('/:id/love', (req, res) => {
console.log("Hitting");
var image_Id = req.params.id;
var fb_id = req.user.id;
var query = {
    "imageId": image_Id
}
var upvote = {
    $inc: {
        vote: 1
    },
    $push: {
        votedBy: req.user.id
    }
}

var downvote = {
    $pull: {
        votedBy: req.user.id
    },
    $inc: {
        vote: -1
    }
}
likeImformation.find({
    "imageId": image_Id
}, {
    "votedBy": fb_id
}).count(function(err, count_num){
    if(count_num===0){
        likeImformation.findOneAndUpdate(query, upvote, function (err, voted) {
            if (err) {
                res.status(404)
            } else {
                console.log("upvoted");
                res.send("upvoted");
            }
        });
    }
    else if(count_num>0){
        console.log(count_num);
        likeImformation.findOneAndUpdate(query, downvote, function (err, voted) {
            if (err) {
                res.status(404)
            } else {
                console.log("downupvoted");
                res.send("downvoted");
            }
        });
    }
})

问题是我无法编写查询,它将搜索文档,然后在文档中搜索数组元素并将其与“votedBy”匹配。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    我们可以在 MongoDB 中使用and 编写查询

    {$and:[{ "imageId": image_Id }, { "votedBy": fb_id }]}

    它会按预期工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 2011-05-24
      相关资源
      最近更新 更多