I applied the $match condition but the response is neither getting fitter nor getting an error. I want fileted records where I pass the page_id and expectation all versions detailed as those mapped with the passed page_id.
Here is my code version model
const mongoose = require("mongoose");
const versionSchema = new mongoose.Schema({
version_name: { type: String, required: true },
version_slug: { type: String, required: true },
is_active: { type: Boolean, required: true },
is_deleted: { type: Boolean, required: true }
}, {
timestamps: true,
versionKey: false
});
module.exports = mongoose.model("version", versionSchema);
pages version model
const mongoose = require("mongoose");
const { Schema } = mongoose;
const pageSchema = new mongoose.Schema({
page_id: { type: Schema.Types.ObjectId, ref: 'pages', require: true },
version_id: { type: Schema.Types.ObjectId, ref: 'versions', require: true },
}, {
timestamps: true,
versionKey: false
});
module.exports = mongoose.model("pageVersion", pageSchema);
controller
pageversions.aggregate([
{
$lookup: {
from: "versions",
localField:"version_id",
foreignField:"_id",
as: "version"
}
},
{ $unwind: "$version" },
{
$project: {
page_id:1,
version_name: "$version.version_name",
virsion_slug: "$version.version_slug",
is_active: "$version.is_active"
}
}
]);
};
getting response
[
{
"_id": "64b77c1f2712e47f8211aae2",
"page_id": "64b77c1f2712e47f8211aae0",
"version_name": "V2",
"virsion_slug": "v2",
"is_active": true
},
{
"_id": "64b78219a56c70b185045f7b",
"page_id": "64b77c1f2712e47f8211aae0",
"version_name": "V1",
"virsion_slug": "v1",
"is_active": true
},
{
"_id": "64b786251a4b4aa03e869adb",
"page_id": "64b786251a4b4aa03e869ad9",
"version_name": "V1",
"virsion_slug": "v1",
"is_active": true
}
]
Expected Response
[
{
"_id": "64b77c1f2712e47f8211aae2",
"page_id": "64b77c1f2712e47f8211aae0",
"version_name": "V2",
"virsion_slug": "v2",
"is_active": true
},
{
"_id": "64b78219a56c70b185045f7b",
"page_id": "64b77c1f2712e47f8211aae0",
"version_name": "V1",
"virsion_slug": "v1",
"is_active": true
}
]
I want all version names whose page_id value is "64b77c1f2712e47f8211aae0"
I'm new to Node kindly help.
here is collection details
collection: pageversions
collections:versions
To filter the results by page_id
, you should add a $match
stage at the beginning of the aggregate
function.
Try
pageversions.aggregate([
{
$match: {
page_id: mongoose.Types.ObjectId("64b77c1f2712e47f8211aae0")
}
},
{
$lookup: {
from: "versions",
localField:"version_id",
foreignField:"_id",
as: "version"
}
},
{ $unwind: "$version" },
{
$project: {
page_id:1,
version_name: "$version.version_name",
virsion_slug: "$version.version_slug",
is_active: "$version.is_active"
}
}
]);