使用Nodejs,Express我想将数据作为整数存储到数据库中并找到Mean。目前,数据(名称和校园)都存储为String,当$ avg用于查找平均值时,db返回null值。数据库中的表是Name和Campus。名称必须为String,Campus必须为整数。 $ avg在Campus with Same Names上执行。 这是我的server.js文件
const express = require('express');
var path = require('path');
const bodyParser = require('body-parser')
const MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb://dbname:passw@d1111.mlab.com:11111/rank', (err, database) => {
if (err) return console.log(err)
db = database
app.listen(8080, () => {
console.log('listening on 8080')
})
})
const app = express();
app.set('view engine', 'ejs')
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
db.collection('colleges').find().toArray((err, result) => {
if (err) return console.log(err)
// renders index.ejs
res.render('index.ejs', {colleges: result})
})
})
app.get('/answers', (req, res) => {
db.collection('colleges').find().toArray((err, result) => {
if (err) return console.log(err)
// renders index.ejs
res.render('index.ejs', {colleges: result})
})
})
app.use(bodyParser.urlencoded({extender: true}))
app.post('/colleges', (req, res) =>{
db.collection('colleges').save(req.body, (err, result) =>{
if (err) return console.log(err)
console.log('saved to database')
console.log(JSON.stringify(req.body))
res.redirect('/')
})
})
这是我的index.ejs文件有这个表单
<form action="/colleges" method="POST">
<input type="text" placeholder="name" name="name">
<input type="number" placeholder="campus" name="campus">
<button type="submit">Submit</button>
</form>
计算平均值的代码
db.colleges.aggregate([
{ $match: { college: "RVCE"}},
{ $group: {_id:"campus", total: {$avg: "$campus"}}}
])
答案 0 :(得分:0)
我猜你可以做到这一点,
app.post('/colleges', (req, res) =>{
req.body.campus = parseInt(req.body.campus);
db.collection('colleges').save(req.body, (err, result) =>{
if (err) return console.log(err)
console.log('saved to database')
console.log(JSON.stringify(req.body))
res.redirect('/')
});