I'm feeling a bit lost here. I'm attempting to search for documents using the $function operator, as outlined in this S_function documentation.
Here is my model:
const newsSchema = new mongoose.Schema({
news_id: {
type: mongoose.Schema.Types.ObjectId,
unique: true,
index: true
},
created_at: { type: String, default: Date.now().toString() },
updated_at: { type: String, default: Date.now().toString() },
Company_id: [{type: mongoose.Schema.Types.ObjectId}],
Stock_id: [{type: mongoose.Schema.Types.ObjectId}],
newsItem: {
date: {type: String},
title: { type: String },
summary: { type: String },
url: { type: String, unique: true },
content: { type: String }
}
};
This is my code attempt:
newsModel.aggregate([
{$match: {$function: {
body: matchArrToArr(matchArr, Company_id),
args: [ "$Company_id" ],
lang: "js"
}}}
])
The variable matchArr comes from the surrounding function and Company_id is supposed to refer to the array 'Company_id' from the news document. However, upon executing the function, I receive an error stating 'Company_id is not defined'. It makes sense because I never define it. How can I properly reference the Company_id field within the function?
I also attempted using find($expr:{$function:... with no success, as well as $where:... with this.Company_id. In the first case, I received the same error. In the second case, 'this' refers to the state of my calling JavaScript function rather than the DB document.
My goal is to retrieve all documents where one of the IDs in the Company_id array matches one of the IDs I provide. If there's a more efficient way to achieve this without using $function, I'm open to suggestions. However, I'm also keen on understanding what I may be doing wrong with my $function expression.
Thank you!