猫鼬查找具有多个可选字段

问题描述 投票:0回答:1

我是猫鼬的新手,目前正在编写一个应用程序以学习它。我有一个Artist Schema和一个具有多个可选字段的表单。例如,用户可以输入姓名,最小年龄并搜索模型,而无需填写其他表单字段。在控制器上,我通过req.body对象获取表单中的所有字段,并拥有一个带有多个if对象的查询对象,如果我检查该属性是否未定义,是否将其作为对象放入对象中属性,并将对象传递给find方法。问题是当我填写最低年龄并将查询属性query.min_age = { $gte: min_age}放入$ gte时,$ gte转换为字符串,结果无法正确运行find方法。

猫鼬模型

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;

控制器

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
        })
    });
});

The image below is depicting the string $gte when i console it

javascript node.js mongodb express mongoose
1个回答
0
投票

JS对象中的键总是强制转换为字符串,因此,$gte作为您发布的屏幕快照上的字符串是没有错的。

关于min_age值,在您的代码中,我看不到任何将其转换为字符串的内容,而猫鼬本身也做得不好。

看来问题出在测试请求中。请检查您是否以POST请求中的数字或字符串形式发送min_age。它应该是数字,否则您需要在控制器中将其转换为数字(例如parseInt()

© www.soinside.com 2019 - 2024. All rights reserved.