51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

与MongoDB建立快速连接并设计API

英文:

Express Connection With MongoDB and Designing APIs

问题 {#heading}

var express = require("express");
var cors = require("cors");
var mongoClient = require("mongodb").MongoClient;

var connectionString = "mongodb://127.0.0.1:27017";

var app = express();
app.use(cors());
app.use(express.urlencoded({
  extended: true
}));
app.use(express.json());

app.get("/getusers", (req, res) => {
  mongoClient.connect(connectionString, (err, clientObj) => {
    if (!err) {
      var database = clientObj.db("reactdb");
      database.collection("tblusers").find({}).toArray((err, documents) => {
        if (!err) {
          res.send(documents);
        }
      });
    }
  });
});

app.post("/registeruser", (req, res) => {
  var userdetails = {
    UserId: req.body.UserId,
    UserName: req.body.UserName,
    Password: req.body.Password,
    Age: parseInt(req.body.Age),
    Mobile: req.body.Mobile,
    Subscribed: req.body.Subscribed === "true" ? true : false
  };
  mongoClient.connect(connectionString, (err, clientObj) => {
    if (!err) {
      var database = clientObj.db("reactdb");
      database.collection("tblusers").insertOne(userdetails, (err, result) => {
        if (!err) {
          console.log("Record Inserted...");
          res.redirect("/getusers");
        }
      });
    }
  });
});

app.listen(4000);
console.log("Server Started : http://127.0.0.1:4000");

Note: I've removed the HTML tags and escaped characters from your code for clarity. Please ensure that your MongoDB server is running and that the database and collection exist with the specified names ("reactdb" and "tblusers") for this code to work correctly. If it still doesn't work, you should check for any error messages in your console to debug the issue further. 英文:

var express = require("express");
var cors = require("cors");
var mongoClient = require("mongodb").MongoClient;
var connectionString = "mongodb://127.0.0.1:27017";
var app = express();
app.use(cors());
app.use(express.urlencoded({
extended:true
}));
app.use(express.json());
app.get("/getusers", (req, res)=>{
mongoClient.connect(connectionString, (err, clientObj)=>{
if (!err) {
var database = clientObj.db("reactdb");
database.collection("tblusers").find({}).toArray((err, documents) => {
if (!err) {
res.send(documents);
}
})
}
})
});
app.post("/registeruser", (req, res)=>{
var userdetails = {
UserId: req.body.UserId,
UserName: req.body.UserName,
Password: req.body.Password,
Age: parseInt(req.body.Age),
Mobile: req.body.Mobile,
Subscribed: (req.body.Subscribed === "true")?true:false
};
mongoClient.connect(connectionString,(err, clientObj)=>{
if(!err){
var database = clientObj.db("reactdb");
database.collection("tblusers").insertOne(userdetails,(err, result)=>{
if(!err){
console.log("Record Inserted...");
res.redirect("/getusers");
}
})
}
})
})
app.listen(4000);
console.log("Server Started : http://127.0.0.1:4000");

I made this API inside the server folder named api.js and then used express and MongoDB. I tried to Connect to MongoDB and show the records on the screen, but it keeps on loading the site when I type http://127.0.0.1:4000/getusers and hit <kbd>enter</kbd> and doesn't show anything. I don't know why it is happening.

答案1 {#1}

得分: 0

这是工作示例:

const express = require("express");
const app = express();
const { MongoClient } = require("mongodb");
const cors = require('cors');
const url = "mongodb://localhost:27017";
const client = new MongoClient(url);

const PORT = 5000;
// 数据库名称
const dbName = "reactdb";
app.use(cors());
app.use(express.urlencoded({
  extended:true
}));

app.use(express.json());

client
  .connect()
  .then(() => {
    console.log("数据库连接成功");
  })
  .catch(() => client.close());

app.get("/getusers", async (req, res) => {
  var database = client.db(dbName);
  let result = await database.collection("tblusers").find().toArray();
  return res.status(200).json({
    msg: "记录成功获取",
    data: result,
  });
});

app.post("/registeruser", async (req, res) => {
  let userdetails = {
    UserName: req.body.UserName,
    Password: req.body.Password,
    Age: parseInt(req.body.Age),
    Mobile: req.body.Mobile,
    Subscribed: req.body.Subscribed === "true" ? true : false,
  };

  var database = client.db(dbName);
  let result = await database.collection("tblusers").insertOne(userdetails);

  if (result.acknowledged) {
    return res.status(200).json({
      msg: "记录成功插入",
    });
  }

  res.status(400).json({ msg: "内部服务器错误" });
});

app.listen(PORT, () => {
  console.log("服务器监听在端口:" + PORT);
});

希望这对您有所帮助。 英文:

Here is the working example :

<!-- begin snippet: hide: false console: true babel: false -->

<!-- language: lang-js -->

const express = require(&quot;express&quot;);
const app = express();
const { MongoClient } = require(&quot;mongodb&quot;);
const cors = require(&#39;cors&#39;);
const url = &quot;mongodb://localhost:27017&quot;;
const client = new MongoClient(url);
const PORT = 5000;
// Database Name
const dbName = &quot;reactdb&quot;;
app.use(cors());
app.use(express.urlencoded({
extended:true
}));
app.use(express.json());
client
.connect()
.then(() =&gt; {
console.log(&quot;database connected successfully&quot;);
})
.catch(() =&gt; client.close());
app.get(&quot;/getusers&quot;, async (req, res) =&gt; {
var database = client.db(dbName);
let result = await database.collection(&quot;tblusers&quot;).find().toArray();
return res.status(200).json({
msg: &quot;record fetched successfully&quot;,
data: result,
});
});
app.post(&quot;/registeruser&quot;, async (req, res) =&gt; {
let userdetails = {
UserName: req.body.UserName,
Password: req.body.Password,
Age: parseInt(req.body.Age),
Mobile: req.body.Mobile,
Subscribed: req.body.Subscribed === &quot;true&quot; ? true : false,
};
var database = client.db(dbName);
let result = await database.collection(&quot;tblusers&quot;).insertOne(userdetails);
if (result.acknowledged) {
return res.status(200).json({
msg: &quot;record inserted successfully&quot;,
});
}
res.status(400).json({ msg: &quot;internal server error&quot; });
});
app.listen(PORT, () =&gt; {
console.log(&quot;server listening on : &quot; + PORT);
});

<!-- end snippet -->


赞(1)
未经允许不得转载:工具盒子 » 与MongoDB建立快速连接并设计API