如何阻止MongoDB对我的数据进行排序?

e0bqpujr  于 2023-01-20  发布在  Go
关注(0)|答案(1)|浏览(108)

我试图创建一个纸牌游戏,但我卡在点返回卡与MongoDB:玩家有30张卡,当点击一张卡时,卡会做一个平移和旋转的动画来显示卡的值,因为我只需要显示3张卡的值,我需要它们按照选择的顺序结束,但是当我选择它们时,它会按照卡的值排序返回给我;比如说,如果我选1,2,3没问题,但如果我选2,1,3它返回1 2 3。
我试过sort(),但它不起作用,因为正如我所说的,我需要它按选定的顺序返回它们,而不是升序或降序(无论如何,它是在没有sort的情况下排序卡片)。我试过Express Handlebars,但显然它创建了一个数组,所以当我输入例如cards.[0].number;在2,1,3的情况下它仍然返回1而不是2。这是我的代码:

router.post('/cards', (req, res) =>{
        let zahl1 = req.body.zahl1;
        let zahl2 = req.body.zahl2;
        let zahl3 = req.body.zahl3;
        cards.find({"zahl": {$in:[zahl1, zahl2, zahl3]}}, { _id: 0}, function(err, cards) {
       return res.render('cardsGame', {
                cards: cards
               });
        });
    });

由于我有这个问题,我正在使用一个简单的HTML来找出如何解决这个问题:

</form>
  <form method="post" action="/cards" id="bilden">
  <input type="text" id="hallo1" class="w-25">
  <input type="text" id="hallo2" class="w-25">
  <input type="text" id="hallo3" class="w-25">
  <a id="funktioniert" onclick="hinrichten()"><input type="submit" value="cards" class="btn btn-primary"></a>
  <input type="text" name="zahl1" id="zahl1" target="zahl1" class="w-25">
  <input type="text" name="zahl2" id="zahl2" target="zahl2" class="w-25">
  <input type="text" name="zahl3" id="zahl3" target="zahl3" class="w-25">
  </form>
  <script>
  let newTextInput1 = document.getElementById('hallo1');
  let newTextInput2 = document.getElementById('hallo2');
  let newTextInput3 = document.getElementById('hallo3');
  let newAncla = document.getElementById('funktioniert');
  let inputResult1 = document.getElementById('zahl1');
  let inputResult2 = document.getElementById('zahl2');
  let inputResult3 = document.getElementById('zahl3');

    function hinrichten(){
      inputResult1.value = newTextInput1.value;
      inputResult2.value = newTextInput2.value; 
      inputResult3.value = newTextInput3.value;  
    }
  </script>

有没有人能帮我想办法做到这一点?谢谢!

x8diyxa7

x8diyxa71#

单个MongoDB节点按照遇到文档的顺序返回文档,如果使用索引来优化查询,则会按照索引的排序顺序遇到文档。
如果您需要文档按照它们插入数据库的顺序,您可以提示$natural索引,但这意味着每个这样的查询都将是一次集合扫描。
要按照它们在请求中出现的顺序获取它们,您需要在客户端对它们进行排序。
可能是这样的:

router.post('/cards', (req, res) =>{
        let zahl1 = req.body.zahl1;
        let zahl2 = req.body.zahl2;
        let zahl3 = req.body.zahl3;
        let zahls = [zahl1, zahl2, zahl3];
        cards.find({"zahl": {$in:zahls}}, { _id: 0}, function(err, cards) {
            let cardsSort = cards.sort(function(a,b){
                               aidx = zahls.indexOf(a.zahl);
                               bidx = zahls.indexOf(b.zahl);
                               return (aidx - bidx);
                            });
            return res.render('cardsGame', {
                 cards: cardsSort
            });
        });
    });

相关问题