我试图在数组中找到具有某个元素的对象:
所以我的查询如下:
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});
})
});
正在安慰的错误如下:
{ [MongoError: Can't canonicalize query: BadValue $elemMatch needs an Object] name: 'MongoError'}
我的数据库中的对象示例:
{
"_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" ]
}
答案 0 :(得分:1)
通常,在匹配单个数组元素的多个属性时,只需使用$elemMatch
。
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});
})
});
答案 1 :(得分:-1)
您应该尝试以下代码:
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});
})
});