I am using this function
export const getVideoByTag = async (req, res, next) => {
const tags = req.query.tags?.split(",");
try {
const videos = await Video.find({tags: {$in: tags}}).limit(20);
res.status(200).json(videos);
}catch (err) {
next(err);
}
};
The router path is router.get("/tags", getVideoByTag)
And I am using postman with the endpoint {{host}}/videos/tags?tags=js
And in my database videos are like this
{
"_id":{"$oid":"62f02bff4ec6b4df46b3aced"},
"userId":"62eeaaf26595deb49db004b0",
"title":"Second Video",
"description":"test description",
"imgUrl":"https://dsafawefas.vom",
"videoUrl":"https://heksldawra.com/assets/likes.mp4",
"views":{"$numberInt":"0"},
"tags":["['js', 'horse']"],
"likes":[],
"disLikes":[],
"createdAt":{"$date":{"$numberLong":"1659907071761"}},
"updatedAt":{"$date":{"$numberLong":"1659907071761"}},
"__v":{"$numberInt":"0"}
}
The problem
You can clearly see that there's a js tag inside the video schema inside my db, but still still it's returning empty array []
when I use get request inside the postman
CodePudding user response:
Your query seems correct but I think there might be an issue with how you are populating your tags
.
It doesn't look like its a true array. You are storing the text without actually converting it to an array.
For instance, here is a sample document I just stored and retrieved. Notice the difference in tags component:
{
"_id" : ObjectId("62f10768c20220d872336a6c"),
"tags" : [
"js",
"horse"
]
}
CodePudding user response:
When you update your document, don't just use $push: {field: array}
, you need to use $each
e.g.
const updatedTags = ["php", "js"]
..... $push: { tags: { $each: updatedTags }} ....
Once you update your document correctly, you should be able to perform your query and get desire documents.