[英]Mongoose find with multiple and optional fields
我是 mongoose 的新手,目前我正在編寫一個應用程序來學習它。 我有一個藝術家模式和一個使用多個可選字段進行搜索的表單。 例如,用戶可以輸入姓名、最小年齡並在 model 中進行搜索,而無需填寫其他表單字段。
On the controller I take all the fields from the form through the req.body object and I have a query object which with multiple if statements I check whether or not the property is not undefined, and if not I put it in the object as a屬性和 object 被傳遞給 find 方法。
問題是當我填寫最小年齡並將查詢 object 這個屬性query.min_age = { $gte: min_age}
$gte 轉換為字符串時,因此無法正確運行 find 方法。
Mongoose Model
const mongoose = require("mongoose");
const AlbumSchema = require("./album")
const CompanySchema = require("./company")
const Schema = mongoose.Schema;
const ArtistSchema = new Schema({
name: String,
age: Number,
yearsActive: Number,
albums: [AlbumSchema],
company:[{type: Schema.Types.ObjectId, ref: "Company"}]
});
const Artist = mongoose.model("artist", ArtistSchema);
module.exports = Artist;
Controller
app.post("/", (req, res, next) => {
const name = req.body.name;
const min_age = req.body.min_age;
const min_active = req.body.min_active;
const sort = req.body.sort;
const query = {};
if(name) {
query.name = name;
}
if(min_age) {
query.min_age = { $gte: min_age};
}
if(min_active) {
qyery.min_active = {gte: min_active};
}
Artist.find(query).
sort(sort)
.then( artists => {
res.render("index", {
artists: artists
})
});
});
JS 對象中的鍵始終轉換為字符串,因此$gte
在您發布的屏幕截圖中作為字符串沒有任何問題。
至於min_age
值,在您的代碼中,我看不到任何可以將其轉換為字符串的內容,並且 mongoose 本身也沒有這樣做。
看起來問題出在測試請求中。 請檢查您是否將min_age
作為 POST 請求中的數字或字符串發送。 它應該是一個數字,否則您需要將其轉換為 controller 中的數字(例如使用parseInt()
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.