简体   繁体   中英

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.

With SubscriberList just being an array of strings you can simply do:

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});
})
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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