【问题标题】:Can not fetching the exact value with mongoose无法用猫鼬获取确切的值
【发布时间】:2020-06-12 21:18:09
【问题描述】:

我想使用 mongoose 从 mongodb 获取数据并将其作为响应发送,但我没有得到确切的答案,我的错误是什么?

我的代码如下:

首先我的模型文件: * 我正在使用 create() 批量插入数据

const express = require('express');
const mongoose= require('mongoose');

const Schema = mongoose.Schema;

const ourDataSchema = new Schema ({
   rank : Number,
   totalPoints : Number
});

const rankTotalpoint = mongoose.model("rankTotalpoint", ourDataSchema);

const ourData = [
     {rank : 1, totalPoints  : 2000},
     {rank : 2, totalPoints  : 1980},
     {rank:  3, totalPoints  : 1940},
     {rank:  4, totalPoints  : 1890},
     {rank : 5, totalPoints  : 1830},
     {rank : 6, totalPoints  : 1765},
     {rank : 7, totalPoints  : 1600},
     {rank : 8, totalPoints  : 1565},
     {rank : 9, totalPoints  : 1465},
     {rank : 10, totalPoints : 1450}
];


rankTotalpoint.create(ourData, function (error, data) {
    if (error) {
        console.log(error)
    }
    else {
        console.log('saved!');
    }
});


exports.result = function (param) {
     const finalresult = rankTotalpoint.aggregate([
        {
          $project: {
            diff: {
              $abs: {
                $subtract: [
                  param, // <<<----------------------- THIS IS THE USER SUPPLIED VALUE 
                  "$totalPoints"
                ]
              }
            },
            doc: "$$ROOT"
          }
        },
        {
          $sort: {
            diff: 1
          }
        },
        {
          $limit: 1
        },
        {
          $project: {
            _id: 0,
           rank: "$doc.rank"
          }
        }
      ])
   return finalresult;
};

还有我的控制器文件代码,我将上面的(结果)函数导入到它:

const express = require('express');

const model = require('../model/logic');

exports.index = (req, res, next) => {
    res.status(200).json({message : 'INSERT INPUTS HERE'});
    };


  exports.getUserData = (req, res, next) => {
     const literature = req.body.literature * 4;
     const arabic = req.body.arabic * 2;
     const religion = req.body.religion * 3;
     const english = req.body.english * 2;
     const math = req.body.math * 4;
     const physics = req.body.physics * 3;
     const chemistry = req.body.chemistry *2;

     //user supplied value
     const TOTALPOINT = literature + arabic + religion + english + math + physics + chemistry;

     let result = model.result(TOTALPOINT); 
     res.status(200).json(result); 
  };

最后这就是我从邮递员那里得到的回复:

{
    "_pipeline": [
        {
            "$project": {
                "diff": {
                    "$abs": {
                        "$subtract": [
                            0,
                            "$totalPoints"
                        ]
                    }
                },
                "doc": "$$ROOT"
            }
        },
        {
            "$sort": {
                "diff": 1
            }
        },
        {
            "$limit": 1
        },
        {
            "$project": {
                "_id": 0,
                "rank": "$doc.rank"
            }
        }
    ],
    "options": {}
}

我想得到什么? 我想根据我得到的用户输入(TOTALPOINT)获得一个 rank,所以我不想发送上述响应,而只是想将排名发回给用户。 如果用户值与 totalpoints 匹配,则将其 rank 作为响应发送,如果确切值不存在,则查找最接近的 totalPoints strong> 并将排名作为响应发送。

像这样:

 [
  {
    "rank": 5
  }
]

谢谢

【问题讨论】:

  • 除非我遗漏了什么,否则你已经拥有了你想要的东西。Try changing the value on line 7 to an 'exact'/existing totalPoints value 它会返回该 totalPoints 值的排名......提供一些不存在的东西,并且它返回最接近的......
  • 你的现场演示代码正是我所寻找的,但是当我在上面发布的项目中编写它时,它不起作用,我不知道我的错误是什么, 你能检查我的代码吗?
  • 这就是你要找的东西吗?
  • 您介意接受我的回答吗?如果我帮助了你,你为什么不帮助我??

标签: node.js database mongodb mongoose response


【解决方案1】:

您的问题是因为 Mongoose 是基于 Promise/async 的。您没有在等待任何事情,因此您的代码返回了一个尚未由您的查询设置的变量..

我正在使用 2 个文件进行测试:myMongoose.jsindex.js..

// myMongoose.js

// ** CODE THAT SAVES DATA TO DATABASE HAS BEEN REMOVED FOR BREVITY **

require('dotenv').config();
const mongoose = require('mongoose');

const RankTotalpointSchema = new mongoose.Schema({
  rank: Number,
  totalPoints: Number
});

mongoose.set('useCreateIndex', true);

const mongoConnection = mongoose.createConnection(process.env.MONGO_DB_STRING, {
  useUnifiedTopology: true,
  useNewUrlParser: true,
  useFindAndModify: false,
});

const RankTotalpoint = mongoConnection.model("RankTotalpoint", RankTotalpointSchema, 'Testing');

/**
 * ~~~~~~ **** THIS HAS TO BE AN ASYNC FUNCTION **** ~~~~~~
 */
exports.result = async function (param) {
  const finalresult = await RankTotalpoint.aggregate([{
      $project: {
        diff: {
          $abs: {
            $subtract: [
              param, // <<<----------------------- THIS IS THE USER SUPPLIED VALUE 
              "$totalPoints"
            ]
          }
        },
        doc: "$$ROOT"
      }
    },
    {
      $sort: {
        diff: 1
      }
    },
    {
      $limit: 1
    },
    {
      $project: {
        _id: 0,
        rank: "$doc.rank"
      }
    }
  ])
  return finalresult;
};

...然后在index.js:

// index.js

const { result } = require('./myMongoose');

// Use it like this:
async function init() {
    try {
        const d = await result(1800);
        console.log(d);
    } catch (err) {
        console.error(err);
    }
}

init(); // -> [ { rank: 5 } ]

// --------------------------------------------------------------------

// ...or like this:
(async () => {
    try {
        const d = await result(1800);
        console.log(d); // -> [ { rank: 5 } ]
    } catch (err) {
        console.error(err);
    }
})()

// --------------------------------------------------------------------

// ...or like this:
result(1800)
    .then(d => console.log(d)) // -> [ { rank: 5 } ]
    .catch(err => console.error(err))

【讨论】:

  • 如果我的回答对您有帮助,请考虑将其标记为已接受的答案。就像答案对您有所帮助一样,赞成和接受的答案对我有所帮助。干杯。
猜你喜欢
  • 1970-01-01
  • 2016-11-12
  • 2020-01-11
  • 2016-07-30
  • 2022-12-19
  • 1970-01-01
  • 2021-11-16
  • 2021-10-24
  • 2019-11-30
相关资源
最近更新 更多