我开始使用Mongo数据库。我想在mongo中插入两个变量。因此,在同一个文件
1.-我定义了两个变量
2.-我创建一个函数,返回一个带有两个变量的JSON格式对象
3.-我在Express中创建一个应用程序来填充值的两个变量并将它们发送出去
4.-我连接到Mongo并插入JSON对象,创建一个集合并将第一个参数传递给函数,该函数返回带有两个参数的JSON对象变量。
结果检查控制台:
1.-连接正确
2:还有就是我觉得我有scopes.How的问题会是正确的顺序插入一个JSON对象,但空作用域将mongo集成在一个节点/快速文件中
?
// Express files
var express = require('express');
var app = express();
// Mongo files
var mongodb=require("mongodb")
var MongoClient = mongodb.MongoClient;
var MONGODB_URI="mongodb://user:[email protected]:00000/"
// Variables
var one;
var two;
// JSON object to insert in mongo
var doc=function(one,two){
return{
"one":one,
"two": two
}
}
// App in Express
app.get("new/:which",function(req,res){
one=req.params.which
var randomNum=Math.round(Math.random()*10000)
two=req.headers["x-forwarded-host"]+("/")+randomNum.toString()
res.end(JSON.stringify(doc(one,two)))
})
// Mongo connection and insertion of JSON object
MongoClient.connect(MONGODB_URI,function(err,db){
if (err) {
console.log('Unable to connect to the mongoDB server.
Error:', err);
} else {
console.log('Connection established to', MONGODB_URI);
}
var collection=db.collection("url")
collection.insert(doc(one,two),function(){
if(err) throw err
console.log(JSON.stringify(doc(one,two)))
db.close()
})
})