I'm newer of nodejs, and I want to create API for my porfolio.
I have built API to get all of projects data, and I want to filter which use query after populate.
Project schema
const ProjectSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
},
tags: [
{
type: Schema.Types.ObjectId,
ref: "tag",
},
],
createAt: {
type: Date,
default: Date.now,
},
});
Tag schema
const TagSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
projects: [
{
type: Schema.Types.ObjectId,
ref: "project",
},
],
createAt: {
type: Date,
default: Date.now,
},
});
if ?tags=react, rwd I wish return:
[
{
name: "A Project",
description: "blablabla",
tag: [
{ name: "react" },
{ name: "rwd" },
{ name: "antd" ),
]
createdAt: "2022/2/15"
},
{
name: "B Project",
description: "blablabla",
tag: [
{ name: "react" },
{ name: "rwd" },
{ name: "mui" ),
]
createdAt: "2022/2/15"
},
]
this is my code below:
// ?tags=react, rwd
const tags = req.query.tags.split(",");
const data = await Project.find()
.sort({ number: -1 })
.populate({
path: "tags",
select: "name -_id",
match: { name: { $in: tags } },
});
Can somebody help me to figure it out? thanks!