问题
I'm new to nodejs and currently i'm trying to implement a web application using nodejs and mongodb (mongoose).
I want to select objects within a nested array and parent array based on a property of those objects.
Simply - I need to select Categories which are having valid property as true and sub_services which are having valid property as true. (with in a category there cannot be sub_services which having valid property as false and there cannot be category objects which are having valid property as false.)
Schema
var VendorSchema = new Schema({
_id: {
type: Schema.Types.ObjectId,
ref: "User"
},
services: {
meta_data: {
allowed_category_count: {
type: Number,
default: 1
}
},
categories: [{
_id:false,
valid :{
type: Boolean,
default: false
},
service_category: {
type: Schema.Types.ObjectId,
ref: "ServiceCategory"
},
sub_services :[{
_id:false,
valid :{
type: Boolean,
default: false
},
service : {
type: Schema.Types.ObjectId,
ref: "Service"
}
}]
}]
},
});
Query
router.get('/get_service_details',function(req, res) {
Vendor.findOne({ _id: req.user._id,'services.categories.valid': true,'services.categories.sub_services.valid': true},'services').
exec(function (err, story) {
if (err) {
console.log(err);
return (err);
}
else{
res.send(story);
}
})
});
results from above query
{
"_id": "5a62ea5d7515222464e20016",
"services": {
"categories": [
{
"service_category": {
"_id": "5a609b40c9a5e50d844838bf"
},
"sub_services": [
{
"service": {
"_id": "5a609f7ac9a5e50d844838c1"
},
"valid": true
},
{
"service": {
"_id": "5a609f7ac9a5e50d844838c1"
}
"valid": false
}
],
"valid": true
},
{
"service_category": {
"_id": "5a609b4ac9a5e50d844838c0"
},
"sub_services": [
{
"service": {
"_id": "5a609f84c9a5e50d844838c2"
}
"valid": true
}
],
"valid": false
}
]
}
}
Expected result
{
"_id": "5a62ea5d7515222464e20016",
"services": {
"categories": [
{
"service_category": {
"_id": "5a609b40c9a5e50d844838bf"
},
"sub_services": [
{
"service": {
"_id": "5a609f7ac9a5e50d844838c1"
},
"valid": true
}
],
"valid": true
}
]
}
}
Can any one please help me on this.
回答1:
Use $filter
expression to filter categories as input to $map
to map the output values with $filter
ed sub_services.
Vendor.aggregate([
{"$match":{"_id":mongoose.Types.ObjectId(req.user._id), "services.categories.valid": true, "services.categories.sub_services.valid": true}},
{
"$addFields": {
"services.categories": {
"$map": {
"input": {
"$filter": {
"input": "$services.categories",
"as": "categoryf",
"cond": "$$categoryf.valid"
}
},
"as": "categorym",
"in": {
"service_category": "$$categorym.service_category",
"valid": "$$categorym.valid",
"sub_services":{
"$filter": {
"input": "$$categorym.sub_services",
"as": "sub_services",
"cond": "$$sub_services.valid"
}
}
}
}
}
}
}
])
来源:https://stackoverflow.com/questions/48404006/nodejs-mongoose-select-objects-with-in-nested-arrays-based-on-object-properties