Ok I am confused. I am trying to find documents using the $function operator as described here: S_function.
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 }
}
};
My code attempt:
newsModel.aggregate([
{$match: {$function: {
body: matchArrToArr(matchArr, Company_id),
args: [ "$Company_id" ],
lang: "js"
}}}
])
matchArr is a variable I pass in from the surrounding function and Company_id is supposed to be the array 'Company_id' from the news document. However when I execute the function, the error 'Company_id is not defined' is returned. Which makes sense, as I dont define it but how do I get the Company_id field into the function.
I also tried find($expr:{$function:... with the same result and $where:... with this.Company_id. First case same error. Second case 'this' has the state of my calling JS function and not the DB document.
What I am actually trying to do: I want to return all documents, where one of the ids in the Company_id array matches one of the ids I pass in. If there is a nicer aggregate way without $function, I am open to that. But I also want to understand what I am doing wrong with my $function expression.
Thanks!
bodyproperty. Do not callmatchArrToArrfunction. Replace it with function definition.