I have structured my data in such a way that it is obtained from
localhost:3000/api/notes/[noteTitle]/note2
{
"data": [
{
"_id": "62ff418fa4adfb3a957a2847",
"title": "first-note2",
"note": { "_id": "62ff399da4adfb3a957a2808", "title": "first" },
},
{
"_id": "631af43b054a6aef1a7c4f08",
"title": "first-note22",
"note": { "_id": "62ff399da4adfb3a957a2808", "title": "first" },
},
{
"_id": "631af504054a6aef1a7c4f11",
"title": "second-note22",
"note": { "_id": "62ff3a10a4adfb3a957a2817", "title": "second" },
}
]
}
Upon sending an API request to
localhost:3000/api/notes/first/note2
, I aim to retrieve only the data with the title "first" in the note object.
This is how I attempted to accomplish this on the API pages:
export default async (req, res) => {
const { query: { noteTitle }, method } = req;
switch (method) {
case "GET":
try {
const notes = await Note2.find({"note.title": noteTitle}).populate("note");
res.status(200).json({ success: true, data: notes });
} catch (error) {
console.log(error);
}
break;
default:
res.status(400).json({ success: false });
break;
}
};
However, I am receiving an array of entries instead of the expected two matches. What could be the issue?
Edit: Here is my Note2 schema:
const Note2Schema = new mongoose.Schema({
title: { type: String, unique: true },
note: { type: mongoose.Schema.Types.ObjectId, ref: "Note" },
});
module.exports = mongoose.models.Note2 || mongoose.model("Note2", Note2Schema);
And this is my Note Schema:
const NoteSchema = new mongoose.Schema({
title: { type: String, unique: true }
});
module.exports = mongoose.models.Note || mongoose.model("Note", NoteSchema);
Edit 2: After referring to the mongoose documentation, it appears that populating and filtering based on populated data may not yield the desired results.
Is there a workaround solution for achieving what I intend to do?
Typically, populate() does not support filtering based on properties of the referenced data. For instance, the following query will not return any results even when author is populated.
const story = await Story.
findOne({ 'author.name': 'Ian Fleming' }).
populate('author').
exec();
story; // null