Я пытался использовать операцию crud с использованием узла js и mongodb.crud
, операция работала нормально, но я пытался запустить инструмент post man. Сначала я попытался получить запрос на передачу инструмента post man, но он успешно получил данные.другой запрос выдал ошибку выдачи для
MongoError: Топология была уничтожена.
как решить эту ошибку.
index.js
var express = require('express')
var MongoClient = require('mongodb').MongoClient;
var body_parser = require('body-parser')
const product = require('./routes/product.js')
var app = express()
app.use(body_parser.json())
app.use('/get', product);
app.use('/insert',product)
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
routs / product.js
var express = require('express')
var validate = require('../models/product.js')
const CircularJSON = require('circular-json');
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
var util = require('util')
var ObjectId = require('mongodb').ObjectID// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, { useNewUrlParser: true });
//Get Data from Database
router.get('/', async (req, res,next) => {
try {
await client.connect();
const db = client.db('olc_prod_db');
const r = await db.collection('Ecommerce').find().toArray();
client.close();
res.send(r)
} catch(err) {
console.log(err.stack);
}
});
//Insert Data from Database
router.post('/', async (req, res) => {
try {
await client.connect();
console.log("Connected correctly to server");
const db = client.db('olc_prod_db');
const { error } = validate.validate(req.body);
if (error)
{
return res.status(400).send(error.details[0].message);
}
else
{
let r = await db.collection('Ecommerce').insertOne(req.body);
assert.equal(1, r.insertedCount);
res.send("Inserted Sucessfully")
}
client.close();
} catch(err) {
console.log(err.stack);
}
});
//Get Particular Data from Database
router.get('/:id', async (req, res) => {
try {
await client.connect();
console.log("Connected correctly to server");
const db = client.db('olc_prod_db');
let r = await db.collection('Ecommerce').find({ _id:new ObjectId(req.params.id)}).toArray();
res.send(r)
client.close();
} catch(err) {
console.log(err.stack);
}
});
//Update Data from Database
router.put('/:id', async (req, res) => {
try {
await client.connect();
const db = client.db('olc_prod_db');
const { error } = validate.validate(req.body);
if (error)
{
return res.status(400).send(error.details[0].message);
}
else
{
let r = await db.collection('Ecommerce').updateOne({_id:new ObjectId(req.params.id)},{ $set: req.body});
res.send("Updated Sucessfully")
}
client.close();
} catch(err) {
console.log(err.stack);
}
});
//Delete Data from Database
router.delete('/:id', async (req, res) => {
try {
await client.connect();
const db = client.db('olc_prod_db');
let r = await db.collection('Ecommerce').deleteOne({_id:new ObjectId(req.params.id)});
res.send("Deleted Sucessfully")
client.close();
} catch(err) {
console.log(err.stack);
}
});
module.exports = router;