我想返回数组的一个索引对象,但是当我查询时,它返回所有的文档。
这是我的架构(UserTb)
const userTbSchema = new Schema({
_id: mongoose.Schema.Types.ObjectId,
userId: String,
gender: String
}这是我的另一个Schema(产品)
const productSchema = new Schema({
_id: mongoose.Schema.Types.ObjectId,
product: String,
userTbId: { type: mongoose.Schema.Types.ObjectId, ref: "userTb", required: true },
}它们在另一个js文件中。这是我的Schema(product)的查询结果,不使用Populate。
{
"_id": "5fc4c13f32ab3174acb01234",
"product": "watch",
"userTbId": "5fc4c13f32ab3174acb08540"
},
{
"_id": "5fc4c2d6b3a2a054d4dc1235",
"userId": "car",
"userTbId": "5fc4c2d6b3a2a054d4dc462c"
}这是当我使用Populate时查询我的Schema(product)的结果。
{
"_id": "5fc4c13f32ab3174acb01234",
"product": "watch",
"userTbId": {
"_id": "5fc4c13f32ab3174acb08540",
"userId": "go05111",
"gender": "male"
}
},
{
"_id": "5fc4c2d6b3a2a054d4dc1235",
"userId": "car",
"userTbId": {
"_id": "5fc4c2d6b3a2a054d4dc462c",
"userId": "Chips",
"gender": "female"
}
}我想在proudct中获得唯一的{ "gender“:”男性“}对象,比如...
{
"_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
});
});
});但是结果是什么也没有返回。
我认为这个填充是ObjectId,所以即使使用了userTbId (),当使用find()时,值也不会出现。
我尝试了几种不同的方法,但都不是我想要的效果。
我如何在mongoose中修复它?
你能帮帮我吗?
发布于 2020-12-14 15:52:41
在mongoose中,populate将在find查询的结果集上执行。在您的产品模式中,userTbId是一个对象id,除非填充它,否则它不会有gender属性。为了仅通过使用mongoose来实现您的目标,您可以编写如下查询。首先,你需要找到你的性别和userId的所有userTbIds。然后查询您的产品模式,以获得返回的userTbIds。欢迎修改和优化。
router.get('/:gender', (req, res, next) => {
userTbId.find({
"gender": req.params.gender,
"userId": req.params.userId
}).exec()
.then(docs => {
let ids = docs.map(doc => doc.id);
Product.find({
"userTbId": {$in:ids}
})
.populate({
path: 'userTbId'
})
.exec()
.then(docs => {
res.status(200).json({
docs
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
});
https://stackoverflow.com/questions/65284492
复制相似问题