네, 혼란 스럽습니다. https://docs.mongodb.com/manual/reference/operator/aggregation/function/#exp._S_function에 설명 된대로 $ function 연산자를 사용하여 문서를 찾으려고합니다 .
내 모델 :
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 }
}
};
내 코드 시도 :
newsModel.aggregate([
{$match: {$function: {
body: matchArrToArr(matchArr, Company_id),
args: [ "$Company_id" ],
lang: "js"
}}}
])
matchArr은 주변 함수에서 전달하는 변수이고 Company_id 는 뉴스 문서의 ' Company_id ' 배열이어야합니다 . 그러나 함수를 실행하면 ' Company_id is not defined ' 오류 가 반환됩니다. 나는 그것을 정의하지 않았지만 어떻게 Company_id 필드를 함수에 가져 오는지 이해가 됩니다.
또한 find ($ expr : {$ function : ... 같은 결과와 $ where : ... with this.Company_id . 첫 번째 경우 동일한 오류. 두 번째 경우 'this' 에는 내 호출 JS 함수의 상태가 있으며 DB 문서가 아닙니다.
내가 실제로하려고하는 것 : Company_id 배열의 ID 중 하나가 내가 전달하는 ID 중 하나와 일치하는 모든 문서를 반환하고 싶습니다. $ function없이 더 좋은 집계 방법이 있다면 그것에 대해 열려 있습니다. 그러나 나는 또한 내 $ function 표현식에서 내가 뭘 잘못하고 있는지 이해하고 싶습니다.
감사!
이것이 당신이 원하는 것입니다.
let someCompany_id = "60278ce8b370ff29b83226e7";
db.news.find(
{
$expr: {
$function: {
body: function(company_ids, someCompany_id) {
let _ids= company_ids.map(company_id => company_id.valueOf());
return _ids.includes(someCompany_id);
},
args: ["$company_id", someCompany_id],
lang: "js"
}
}
}
)
그러나 이것은 다음과 같이 쉽게 할 수 있습니다.
db.news.find({
company_id: {
$in: [someCompany_id]
}
});
그렇다면 왜 함수를 전달하고 싶습니까?
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다