長話短說,我的 MongoDB 資料庫中有一個帖子集合,并且使用node.js,express和mongoose,我正在嘗試使用$where方法查找所有檔案。
所以我嘗試了這個,它完美地作業,所有的結果,如果他們的名字包括Jo被回傳。
app.get("/posts", (req, res) => {
const nameSearch = "Jo";
Post.find({
$where: function () {
return this.name.includes("Jo");
},
}).then((data) => res.send(data));
});
但是如果我做這樣的事情,它會給我一個錯誤
app.get("/posts", (req, res) => {
const nameSearch = "Jo";
Post.find({
$where: function () {
return this.name.includes(nameSearch);
},
}).then((data) => res.send(data));
});
另外,如果我這樣做,它會說$where需要一個字串或一個函式。
function runThis(post) {
return post.name.includes("Jo");
}
app.get("/posts", (req, res) => {
Post.find({
$where: runThis(this),
}).then((data) => res.send(data));
});
我認為更奇怪的是,如果我將內部的函式更改$where為 an arrow function,無論我在函式中放入什么,它都會回傳所有結果
app.get("/posts", (req, res) => {
const nameSearch = "Jo";
Post.find({
$where: () => {
return this.name.includes("Jo");
},
}).then((data) => res.send(data));
});
uj5u.com熱心網友回復:
警告:我不使用 Mongoose 或 MongoDb。
但是檔案說您傳遞的函式$where不是在本地執行的,而是在 Mongoose 服務器上執行的。所以它無權訪問變數。
但是搜索 ( 1 , 2 ) 表明在欄位中查找子字串的常用方法是使用$regex. 如果是這樣,并且您有一個用戶輸入的字串(其中可能包含對 具有特殊含義的字符$regex),您將希望對它們進行轉義。例如:
app.get("/posts", (req, res) => {
const nameSearch = "Jo";
Post.find({
name: {
$regex: new RegExp(escapeRegex(nameSearch)),
}),
}).then((data) => res.send(data));
});
...escapeRegex該鏈接問題的答案來自哪里。(顯然支持 JavaScript 正則運算式物件,以及使用 PCRE 語法的字串。)
如果由于某種原因你不能這樣做,你也可以傳遞一個字串 for $where,這樣你就可以動態地創建字串:
app.get("/posts", (req, res) => {
const nameSearch = "Jo";
Post.find({
$where: `this.name.includes(${JSON.stringify(nameSearch)})`,
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}).then((data) => res.send(data));
});
通常,在字串中撰寫 JavaScript 代碼是一個壞主意(即使 Mongoose 必須將您提供的任何函式轉換為字串以將其發送到服務器),但是如果您需要進行這種替換......
uj5u.com熱心網友回復:
檔案中的一些內容
$where 檔案
關于范圍
從 MongoDB 4.4 開始,$where 不再支持已棄用的具有范圍的 BSON 型別 JavaScript 代碼(BSON 型別 15)
你應該避免使用$where
$where 評估 JavaScript 并且不能利用索引。因此,當您使用標準 MongoDB 運算子(例如 $gt 、 $in )表達查詢時,查詢性能會提高。
通常,只有在無法使用其他運算子表達查詢時才應使用 $where。如果您必須使用 $where ,請嘗試至少包含一個其他標準查詢運算子來過濾結果集。單獨使用 $where 需要進行集合掃描。
關于變數
我不知道,但你可以嘗試使用$let
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/512928.html
上一篇:如何使用boto3上傳s3
下一篇:遍歷python字典給出意外行為
