最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

我如何管理并非总是填充的查询参数?

网站源码admin19浏览0评论

我如何管理并非总是填充的查询参数?

我如何管理并非总是填充的查询参数?

我的模型如下:

const replaySchema = new Schema({

    game: {type: String, required:true},
    link: {type: String, required:true,unique: true},
    player1: {type: String, required: true},
    player2: {type: String, required: true},
    character1: {type: String, required: true},
    character2: {type: String, required: true}


},{
    timestamps:true,
});

[我的用户使用与模型相同的值填写表单,在其中他可以将大多数参数留空,例如,他只能填写游戏和player1字段。

在提交表单时,会创建一个新的const,它获取表单中已填充输入的参数和值,然后将其发送到params字段中的后端。

onSubmit(e){
        e.preventDefault();

        const replay = {};

        this.state.game && (replay.game = this.state.game);
        this.state.player1 && (replay.player1 = this.state.player1);
        this.state.player2 && (replay.player2 = this.state.player2);
        this.state.character1 && (replay.character1 = this.state.character1);
        this.state.character2 && (replay.character2 = this.state.character2);

        console.log(replay);

        axios.get("http://localhost:5000/search/",
            {params:replay}).then(response => {
                this.setState({
                    replays: response.data
                })
            }).catch((error) => {
                console.log(error);
        })
    }

并且后端最初将像这样处理它。


router.route('/').get((req,res) => {

    console.log(req.query);

   Replay.find(req.query).then(replays => res.json(replays)).catch(err => res.status(400).json('Error: ' + err));
});

但是,我们决定,当用户在任何一个播放器字段中输入一个值时,无论播放器1还是播放器2,数据库都将返回重播效果更好。如您所见,考虑到所有可选值,用户可以通过填充/不填充每个值而从所有不同选项中得出许多不同的查询。

我的第一个想法是检查用ifs填充哪些值,并根据此值进行不同的查询,但这将意味着大约有16个以上的查询,这听起来不太干净。

然后我考虑了顺序构造一个查询字符串,但是考虑为$ or和$ in使用mongodb结构,试图像那样做几乎就像在很多ifs上这样做。

难道没有更简单的方法吗?谢谢。

回答如下:

最佳实践是将逻辑放在服务器端。在这种情况下,实现您想要的并不难。

请注意,没有通用的“性感”方式来实施特定业务。但是没有理由对实现支持它的逻辑保持警惕。

router.route('/').get((req,res) => {

    console.log(req.query);
    let andConds = [];

    if (req.query.character1) {
        andConds.push({character1: req.query.character1})
    }

    if (req.query.character2) {
        andConds.push({character2: req.query.character2})
    }

    if (req.query.game) {
        andConds.push({game: req.query.game})
    }

    if (req.query.player1 || req.query.player2) {
        let orCond = [];
        if (req.query.player1) {
            orCond.push({player1: req.query.player1})
            orCond.push({player2: req.query.player1})
        }

        if (req.query.player2) {
            orCond.push({player1: req.query.player2})
            orCond.push({player2: req.query.player2})
        }
        andConds.push({$or: orCond})
    }

    //if no conditions exists match all as before.
    Replay.find(andConds.length ? {$and: andConds} : {}).then(replays => res.json(replays)).catch(err => res.status(400).json('Error: ' + err));
});
发布评论

评论列表(0)

  1. 暂无评论