我在 expressjs 中使用 mongodb 和 mongoose
我的資料庫有以下陣列:
_id:6262013fa90e7b533809140d
isactive:true
schedule:Array
0:Object
1:Object
2:Object
3:Object
4:Object
5:Object
6:Object
name:"whatever"
description:"describe somthing"
在我的 expressjs 路線中,我正在嘗試構建這樣的查詢:
app.get("/getmenu", (req, res)=>{
let getdate = new Date()
let getday = getdate.getDay()-1
Category.find({ "schedule.1.availabletoday" : "true" },
function(error, categories){
console.log("categories :", categories)
res.json({"activecategories" : categories})
})
})
這確實有效并回傳了正確的結果,除了我需要下面的行來包含模板文字或等效的東西,讓我解釋一下:
"schedule.1.availabletoday"
我需要用 getday 值替換 1 。如果 getday 值為 0,則查詢將是
"schedule.0.availabletoday"
如果 getday 值為 2,則查詢將查找:
"schedule.2.availabletoday"
那么如何在查詢中包含 getday 值,如下所示:
"schedule.getday.availabletoday"
我試過
"schedule.${getday}.availabletoday"
但它回傳了空結果,我的意思是空的:[]
我試過
"schedule.getday.availabletoday"
查詢回傳空結果:[]
根據 mongodb doc,要搜索陣列元素,我需要在陣列元素查詢周圍加上引號。所以我不能只寫這個:
schedule.getday.availabletoday
我是否需要更新我的節點或 expressjs 應用程式才能使用模板文字,還是我在這里缺少的其他東西?
uj5u.com熱心網友回復:
使用模板字串作為
`schedule.${getday}.availabletoday`
根據您的示例:
app.get("/getmenu", (req, res)=>{
let getdate = new Date()
let getday = getdate.getDay()-1
Category.find({ `schedule.${getday}.availabletoday` : true },
function(error, categories){
console.log("categories :", categories)
res.json({"activecategories" : categories})
})
uj5u.com熱心網友回復:
這應該適合你:
let getdate = new Date();
let day = getdate.getDay()-1;
let query = {};
query[`schedule.${day}.availabletoday`] = true;
Category.find(query, (err, categories)=> {
console.log("categories :", categories)
res.json({"activecategories" : categories})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470256.html
標籤:javascript 节点.js 表示 猫鼬 mongodb查询
上一篇:MongoDB聚合查詢未正確過濾
下一篇:在Array.foreach()的node_modules/ejs/lib/ejs.js中找不到匹配的“<%”標簽