【问题标题】:How to send data to MongoDB that is calculated after page loads?如何将页面加载后计算的数据发送到 MongoDB?
【发布时间】:2016-09-13 19:16:51
【问题描述】:

我将 Node.js 与 Express 和 MongoDB 一起使用。

我有一个页面'/score',它根据前一页上的测验计算用户的分数。 '/score' 路由如下:

app.get('/score', stormpath.getUser, function(req, res) {
    var quiz = req.session.mostRecentQuiz;
    db.collection('quizzes').find(quiz).toArray(function (err, docs) {
        assert.equal(err, null);
        var quiz;
          docs.forEach(function (doc) {
            quiz = doc.quiz;
        });
        res.render('score', {quiz: quiz});
    });
    db.collection('users').update({user: req.user.username}, { $set: {"mostRecentQuiz": quiz } }, function (err, result) {
        if (err) throw err;
        console.log(result);
    } );
});

从数据库获得测验答案后,我在 /score 页面上使用一些客户端 JavaScript 来计算用户的分数,然后将其报告给用户。但是,我想在我的 MongoDB 中获得同样的分数,但我不知道如何最好地做到这一点。

我可以使用 AJAX 来完成此操作,还是重定向到新页面更好?

【问题讨论】:

  • 如果可以在服务器端进行分数计算,请这样做,将其保存在数据库中,然后将预先计算的分数返回给前端。所有这一切,在一个请求中完成。
  • 如果你真的需要在前端进行计算,你可以有效地使用ajax将数据发送回另一个url。

标签: javascript ajax node.js mongodb express


【解决方案1】:

如果您已经在使用 Express,最简单的方法是定义更新分数的路径。然后您可以通过 AJAX 将数据发送到服务器。 为了解析请求参数,安装body-parser 模块。

服务器:

var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.put('/score', stormpath.getUser, function (req, res) {
   console.log(req.body); // there should be your received data

  // save it to the database
  db.collection('yourcollection').updateOne(
      {}, // your query for updating the data in the wished field
      function(err, results) {
        if(err) { return res.json(err); }; 
        return res.json(results);
   });
}); 

客户端 - 如果您使用 jQuery:

$.ajax({
    url: '/score',
    type: 'PUT',
    contentType: 'application/json',
    data: {'score':1000}, // put here your data to send it to the server
    success: function(data){
        console.log(data);
    }
});

一些文档:

MongoDB 更新:https://docs.mongodb.com/getting-started/node/update/

jQuery AJAX:https://api.jquery.com/jquery.ajax/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多