Node.js 如何在mongoose中的populate()中获取值?
我想返回数组的一个索引对象, 但是当我查询时,它返回给我所有的文档 这是我的模式(userTb) 这是我的另一个模式(产品) 它们在另一个js文件中。 这是查询“我的架构(产品)”不使用“填充”的结果Node.js 如何在mongoose中的populate()中获取值?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我想返回数组的一个索引对象, 但是当我查询时,它返回给我所有的文档 这是我的模式(userTb) 这是我的另一个模式(产品) 它们在另一个js文件中。 这是查询“我的架构(产品)”不使用“填充”的结果 { "_id": "5fc4c13f32ab3174acb01234", "product": "watch", "userTbId": "5fc4c13f32ab
{
"_id": "5fc4c13f32ab3174acb01234",
"product": "watch",
"userTbId": "5fc4c13f32ab3174acb08540"
},
{
"_id": "5fc4c2d6b3a2a054d4dc1235",
"userId": "car",
"userTbId": "5fc4c2d6b3a2a054d4dc462c"
}
{
"_id": "5fc4c13f32ab3174acb01234",
"product": "watch",
"userTbId": {
"_id": "5fc4c13f32ab3174acb08540",
"userId": "go05111",
"gender": "male"
}
},
{
"_id": "5fc4c2d6b3a2a054d4dc1235",
"userId": "car",
"userTbId": {
"_id": "5fc4c2d6b3a2a054d4dc462c",
"userId": "Chips",
"gender": "female"
}
}
这是我使用Populate时查询模式(产品)的结果
{
"_id": "5fc4c13f32ab3174acb01234",
"product": "watch",
"userTbId": "5fc4c13f32ab3174acb08540"
},
{
"_id": "5fc4c2d6b3a2a054d4dc1235",
"userId": "car",
"userTbId": "5fc4c2d6b3a2a054d4dc462c"
}
{
"_id": "5fc4c13f32ab3174acb01234",
"product": "watch",
"userTbId": {
"_id": "5fc4c13f32ab3174acb08540",
"userId": "go05111",
"gender": "male"
}
},
{
"_id": "5fc4c2d6b3a2a054d4dc1235",
"userId": "car",
"userTbId": {
"_id": "5fc4c2d6b3a2a054d4dc462c",
"userId": "Chips",
"gender": "female"
}
}
我想得到proudct中唯一的{“性别”:“男性”}对象,比如
{
"_id": "5fc4c13f32ab3174acb01234",
"product": "watch",
"userTbId": {
"_id": "5fc4c13f32ab3174acb08540",
"userId": "go05111",
"gender": "male"
}
}
所以我这样问
router.get('/:gender', (req, res, next) => {
Product.find({
"userTbId.gender": req.params.gender
})
.populate({
path: 'userTbId',
match: {
userId: req.params.userId
}
})
.exec()
.then(docs => {
res.status(200).json({
docs
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
});
但结果是什么也没有返回
我认为userTbId是ObjectId,因此即使使用了populate(),使用find()时也不会出现该值
我尝试了几种不同的方法,但没有达到我想要的效果
我怎样才能在猫鼬中修复它
您能帮助我吗?在mongoose中,将对查找查询的结果集执行填充。 在产品架构中,userTbId是一个对象id,除非填充它,否则它将不具有性别属性。为了仅通过使用mongoose实现您的目标,您可以编写如下查询。首先,您需要找到您的性别和userId的所有usertbid。然后查询产品架构以获取返回的usertbid。欢迎进行更正和优化
router.get('/:gender',(req,res,next)=>{
userTbId.find({
“性别”:要求参数性别,
“userId”:req.params.userId
}).exec()
。然后(docs=>{
让id=docs.map(doc=>doc.id);
Product.find({
“userTbId”:{$in:ids}
})
.填充({
路径:“userTbId”
})
.exec()
。然后(docs=>{
res.status(200).json({
文件
});
})
.catch(错误=>{
res.status(500).json({
错误:错误
});
});
})
.catch(错误=>{
res.status(500).json({
错误:错误
});
});
});代码>谢谢。已经解决了。因为这个,我已经痛苦了大约三个星期。非常感谢:DGald解决了您的问题:)