问题是数据库中来自 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 无关
慕尼黑的夜晚无繁华
jeck猫
相关分类