我有一个 users
表,它具有以下数据结构:
[{
userID: 0,
username: 'test0',
petsForSale: [
{ type: 'fish' },
{ type: 'cats' }
],
seekingPets: [
{ type: 'dogs' },
{ type: 'birds' }
]
},
{
userID: 1,
username: 'test1',
petsForSale: [
{ type: 'guinea pigs' },
{ type: 'dogs' },
{ type: 'hamsters' }
],
seekingPets: [
{ type: 'ferrets' }
]
}]
我正在尝试执行一个 GET
,它根据 petsForSale
和 seekingPets
返回匹配的用户。例如,如果用户出售狗
,则它们将显示在 seekingPets
中任何拥有狗
的用户的匹配结果列表中。我已经非常接近了,这是到目前为止我的路由器代码:
router.get('/:id/findmatches', function(req, res) {
var db = req.db;
var collection = db.get('users');
var uid = req.params.id;
//var seeking_pets = collection.find({ userID: uid }, { seekingPets: 1 });
//var seeking_pets = collection.find({ userID: uid }, { seekingPets: { type: 1 }});
var seeking_pets = [ 'dogs', 'birds' ]; // *Hard-coded is the only way I can get it to work
collection.find({ petsForSale: { $elemMatch: { type: { $in: seeking_pets }}}}, function(e, docs) {
res.json(docs);
});
});
此代码可以通过 seeking_pets
硬编码编译并正常工作 - 访问 /users/0/findmatches
按预期返回用户 test1
。我一直在从请求中的 userID
中提取 seekingPets
列表,并在 collection.find
中搜索它。这两行注释是我尝试过但没有成功的。我还尝试将 collection
转换为 array
。
最佳答案
由于 find
是一个异步方法,因此您必须实现回调才能获取从数据库返回的值。另请注意,您的硬编码值是字符串,但 SeeingPets 数组是对象。
试试这个:
router.get('/:id/findmatches', function(req, res) {
var db = req.db;
var collection = db.get('users');
var uid = req.params.id;
collection.findOne({ userID: uid }, function(err, user)
var seeking_pets = [].
for (var i = 0; i < user.seekingPets.length; i++) {
seeking_pets.push(user.seekingPets[i].type);
}
collection.find({ petsForSale: { $elemMatch: { type: { $in: seeking_pets }}}}, function(e, docs) {
res.json(docs);
});
});
});
请注意,我使用 findOne
来获取对象而不是数组,并且从该对象中我获取了 SeeingPets 数组。当然,你可以改进这段代码,删除一些可有可无的变量,例如 seeking_pets
,并在找不到 id 时处理数据库错误。
关于javascript - 如何在 MongoDB 中的一个数组中搜索另一个数组中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40322270/