繁体   English   中英

Mongoose 查找多个可选字段

[英]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
        })
    });
});

下图描绘了我控制台时的字符串 $gte:
下图描绘了我控制台时的字符串 $gte

JS 对象中的键始终转换为字符串,因此$gte在您发布的屏幕截图中作为字符串没有任何问题。

至于min_age值,在您的代码中,我看不到任何可以将其转换为字符串的内容,并且 mongoose 本身也没有这样做。

看起来问题出在测试请求中。 请检查您是否将min_age作为 POST 请求中的数字或字符串发送。 它应该是一个数字,否则您需要将其转换为 controller 中的数字(例如使用parseInt()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM