【发布时间】: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
totalPointsvalue 它会返回该 totalPoints 值的排名......提供一些不存在的东西,并且它返回最接近的...... -
你的现场演示代码正是我所寻找的,但是当我在上面发布的项目中编写它时,它不起作用,我不知道我的错误是什么, 你能检查我的代码吗?
-
这就是你要找的东西吗?
-
您介意接受我的回答吗?如果我帮助了你,你为什么不帮助我??
标签: node.js database mongodb mongoose response