首页 > 解决方案 > 无法将从 api 获取的变量添加到数据库

问题描述

问题是数据库中来自 api 请求的数据应该是“0 字段”的字段。我认为这是因为 mongo 在 api 响应位于对象变量中之前将对象插入数据库。所以我想我需要让数据库插入函数等到 api 请求完成。

有谁知道我怎样才能完成这件事?

const express = require('express');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const path = require('path');
const fs = require('fs');
const fetch = require('node-fetch');

var mongodb = require('mongodb')
var mongoDbQueue = require('mongodb-queue')

const url = 'mongodb://localhost:27017/'
const client = new mongodb.MongoClient(url, { useNewUrlParser: true })

const app = express();


// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.set('views', __dirname);

// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));

// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.render('main');
});

app.post('/send', (req, res) => {
  var item = {
  name: req.body.name,
  age: req.body.age,
country: req.body.country,
  isValid:
 fetch(*/normaly working url inside here*/)  
      .then(res => res.json())
      .then(data => isValid = data)
      .then(() => console.log(isValid))

}



client.connect(err => {
    const db = client.db('test')
    const queue = mongoDbQueue(db, 'my-queue')


  queue.add(item, (err, id) => {
 
  })

  })



});



app.listen(3000, () => console.log('Server started...'));

.then(() => console.log(equivalent))给了我正确的价值,所以它与 api 无关

标签: javascriptnode.jsmongodbasynchronous

解决方案


目前尚不清楚您要在这里实现什么,但我的猜测是,当 fetch 承诺已在 /send 路由处解决时,您想添加一个数据库条目。在这种情况下,您需要像这样重构代码:

const express = require('express');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const path = require('path');
const fs = require('fs');
const fetch = require('node-fetch');

var mongodb = require('mongodb')
var mongoDbQueue = require('mongodb-queue')

const url = 'mongodb://localhost:27017/'
const client = new mongodb.MongoClient(url, { useNewUrlParser: true })

const app = express();

// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.set('views', __dirname);

// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));

// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/', (req, res) => {
    res.render('main');
});

app.post('/send', (req, res) => {
    let name = req.body.name;
    let age = req.body.age;
    let country = req.body.country;
    fetch( /* normaly working url inside here */)
        .then(res => res.json())
        .then(data => {
            let item = { name, age, country, isValid: true };
            // data is ready to be used or added to the database at this point:
            client.connect(err => {
                const db = client.db('test')
                const queue = mongoDbQueue(db, 'my-queue')
                queue.add(item, (err, id) => {
                })
            })

        })
        .catch((error) => console.log(error));

});

app.listen(3000, () => console.log('Server started...'));

推荐阅读