Javascript 无法将从api获取的变量添加到数据库
问题是数据库中api请求中的数据应该位于的字段显示为“0字段”。我认为这是因为mongo在对象变量中包含api响应之前将对象插入数据库。因此,我认为需要让数据库插入函数等待api请求完成 有人知道我怎样才能完成这件事吗Javascript 无法将从api获取的变量添加到数据库,javascript,node.js,mongodb,asynchronous,Javascript,Node.js,Mongodb,Asynchronous,问题是数据库中api请求中的数据应该位于的字段显示为“0字段”。我认为这是因为mongo在对象变量中包含api响应之前将对象插入数据库。因此,我认为需要让数据库插入函数等待api请求完成 有人知道我怎样才能完成这件事吗 const express=require('express'); const bodyParser=require('body-parser'); const exphbs=require('express-handlebar'); const path=require('p
const express=require('express');
const bodyParser=require('body-parser');
const exphbs=require('express-handlebar');
const path=require('path');
常数fs=要求('fs');
const fetch=require('node-fetch');
var mongodb=require('mongodb')
var mongoDbQueue=require('mongodb-queue')
常量url=mongodb://localhost:27017/'
const client=new mongodb.MongoClient(url,{useNewUrlParser:true})
常量app=express();
//查看引擎设置
发动机附件(“把手”,exphbs());
应用程序集(“查看引擎”、“把手”);
app.set('views','dirname');
//静态文件夹
app.use('/public',express.static(path.join('public'));
//体解析器中间件
use(bodyParser.urlencoded({extended:false}));
use(bodyParser.json());
应用程序获取(“/”,(请求,请求)=>{
res.render(“main”);
});
app.post('/send',(req,res)=>{
变量项={
名称:req.body.name,
年龄:要求的身体年龄,
国家:req.body.country,
有效期:
fetch(*/normaly working url in here*/)
.then(res=>res.json())
.然后(数据=>isValid=data)
.然后(()=>console.log(isValid))
}
client.connect(err=>{
const db=client.db('test')
const queue=mongoDbQueue(db,‘我的队列’)
添加(项目,(错误,id)=>{
})
})
});
app.listen(3000,()=>console.log('Server started…')代码>问题在于获取API的异步特性。isValid中的值直到稍后的时间点才会解析。此外,您使用的值不正确
下面的代码等待响应,设置值,并在正确的范围内更新db
app.post('/send', (req, res) => {
fetch(*/normaly working url inside here*/)
.then(res => res.json())
.then(isValid => {
var item = {
name: req.body.name,
age: req.body.age,
country: req.body.country,
isValid //same as isValid : isValid
}
client.connect(err => {
if(!err) { // error check
const db = client.db('test');
const queue = mongoDbQueue(db, 'my-queue');
queue.add(item, (err, id) => {})
}
});
});
});
现在还不太清楚你想在这里实现什么,
但我猜,您希望在获取时添加一个数据库条目
承诺已在/发送路线结算。在这种情况下,你需要
像这样重构代码:
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...'));
因此,您基本上需要在/send fetch完成后向数据库添加一个条目,对吗?现在控制台返回Promise{}.Updated。现在您可以访问数据,即获取的结果,并且可以通过item对象将其添加到数据库中。如果fetch导致错误,则必须在catch子句中处理该错误。