简体   繁体   English

如何在mongodb中的数组中查找元素?

[英]How to find an element in an array in mongodb?

I am trying to find the object with a certain element in the array: 我试图在数组中找到具有某个元素的对象:

so my query is as follows: 所以我的查询如下:

router.get('/', function(req, res) {
    var userSubscribed = req.user.email;
    db.posts.find({ "SubscriberList": { $elemMatch: userSubscribed}}, function(err, object){
        if (err) console.log(err);
        else console.log(object);
        res.render('index', { title: 'Home', user: req.user});
    })
});

The err that is being consoled is as follows: 正在控制台的错误如下:

{ [MongoError: Can't canonicalize query: BadValue $elemMatch needs an Object] name: 'MongoError'}

An example of an object in my db: 我的数据库中一个对象的示例:

{ 
    "_id" : ObjectId("5490afa8416841105626cc41"), 
    "post" : { 
        "title" : "Ralph", 
        "category" : "Node", 
        "date" : "2014-12-11", 
        "description" : "Node coming soon!" 
    }, 
    "owner" : "bousamra.ralph@gmail.com", 
    "status" : "active", 
    "category" : "Node", 
    "SubscriberList" : ["alaric@hotmail.com" ]
}

In general, you only need to use $elemMatch when matching multiple properties of a single array element. 通常,只在匹配单个数组元素的多个属性时才需要使用$elemMatch

With SubscriberList just being an array of strings you can simply do: 使用SubscriberList只是一个字符串数组,您可以简单地执行以下操作:

router.get('/', function(req, res) {
    var userSubscribed = req.user.email;
    db.posts.find({ "SubscriberList": userSubscribed }, function(err, object){
        if (err) console.log(err);
        else console.log(object);
        res.render('index', { title: 'Home', user: req.user});
    })
});

You should try this code: 您应该尝试以下代码:

router.get('/', function(req, res) {
var userSubscribed = req.user.email;
db.posts.find({owner:userSubscribed}, function(err, object){
    if (err) console.log(err);
    else console.log(object);
    res.render('index', { title: 'Home', user: req.user});
})
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM