如何从异步函数中获取值

时间:2017-04-29 14:12:00

标签: javascript node.js ajax

使用Ajax从客户端向节点服务器发送数据后,我需要将数据传递给数据库(或保存在节点服务器的变量中),

app.post('/newcart', function(req, res) {
    var strJSON = req.param('strJSON');
    var objJSON = JSON.parse(strJSON);
    var answers = objJSON.answers;
    var correctAnswers = [2, 3, 1];
    var results = {};

    //This is the function i tried using,
    db.collection('cart').insertOne({objJSON}, function (err, doc) {

    //This is just some sample function i used
    for (var i = 0; i < answers.length; i = i + 1) {
        var q = i + 1;
        if (answers[i] === null)
            results["q" + q] = "Unanswered";
        else if (answers[i] == correctAnswers[i])
            results["q" + q] = "Right";
        else
            results["q" + q] = "Wrong";
    }

    var respondWith = results;
    res.status(200);
    return res.send(respondWith);
    });
});

我能够将结果重新发送到前端,但无法将数据保存到nodejs中的数据库(mongoDB)中。

Node.js服务器代码,

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

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/cartdb';

app.post('/newcart', function(req, res) {
        //rest of code

    var strJSON = req.param('strJSON');
    var objJSON = JSON.parse(strJSON);

    //The function i tried using to insert the data into db
    db.collection('cart').insertOne({objJSON}, function (err, doc) {
    var answers = objJSON.answers;
    var correctAnswers = [2, 3, 1];
    var results = {};

    //This can be ignored(code to show a reply on the front end)
    for (var i = 0; i < answers.length; i = i + 1) {
        var q = i + 1;
        if (answers[i] === null)
            results["q" + q] = "Unanswered";
        else if (answers[i] == correctAnswers[i])
            results["q" + q] = "Right";
        else
            results["q" + q] = "Wrong";
    }

    var respondWith = results;
    res.status(200);
    resultIsReady(respondWith);
    return res.send(respondWith);
    });
});
app.use(directory(__dirname));
app.use(express.static(__dirname));

//listen on port 8080 for webserver:
app.listen(8080);

当页面运行并发出ajax请求时,我希望能够将数据保存到数据库中。

PS:我需要一种方法来使用ajax,将数据(json)发送到nodejs,并将数据插入到mongodb中。 一切都会奏效。

1 个答案:

答案 0 :(得分:0)

  

db.collection(&#39; cart&#39;)。insertOne({objJSON},function(err,doc)

在发布的代码中,我看到db在使用前没有准备好,你必须首先连接Mongo,

MongoClient.connect(URL, function (err, db) {
  if (err) {

    return;
  }
  else{
    //here your code comes which uses db.collection....
  }
}