Unable to insert data in MongoDb using Node Js - node.js

I am trying to insert data in MongoDb using NodeJs but before inserting data I want to check whether data is already available in database or not if data is not available then only it should insert data in MongoDb.
Problem - Whenever I am saving data even though it is not available in database it is always showing
response "User exists".
This is what I have done so far:
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const dotEnv = require('dotenv').config();
const MongoClient = require('mongodb').MongoClient;
const dburl = process.env.URL;
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended:true}));
router.post('/saveSalesperson',(req,res) => {
var data = {
email:req.body.username,
password:req.body.password,
type:req.body.type
};
MongoClient.connect(dburl,{useNewUrlParser:true,UseUnifiedTopology:true},(err,client) => {
if(err){
console.log("Error",err);
}
else{
client.db('Mydb').collection('Users').findOne({email:req.body.username},function(err,user){
if(err){
console.log("Error",err);
}
if(user){
res.send("User exists");
}
else{
let collection = client.db("Mydb").collection("Users");
collection.insertOne(data,(err,resp) => {
if(err){
console.log("Error:".red +err);
}
else{
res.send("User created");
}
});
}
});
}
});
});
module.exports = router;
Someone please let me know what I am doing wrong.Any help would be appreciated.
THANKS

Related

data do not insert to mongo with app.post

i use following code that contain get all data get data by id and post data to mongo:
const express = require("express");
const app=express();
const _route=require('./router/router.js')
require('dotenv').config();
require('./Database/config.js');
const bodyParser=require('body-parser');
const router=express.Router();
const port_=process.env.PORT|| 8080;
const product=require('./model/model.js');
const res = require("express/lib/response");
const { db } = require("./model/model.js");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.post('/insert',async(req,res)=>{
const newProduct=new product({
_id:req.query._id,
name:req.query.name,
description:req.query.description
});
try{
await newProduct.save();
res.json(newProduct);
}
catch(err){
res.send(err);
}
});
app.get('/',async(req,res)=>{
try{
const get= await product.find();
res.json(get);
}
catch(err){
res.send(err);
}
});
app.get('/:name',async(req,res)=>{
try{
const get=await product.find({name:req.params.name});
if(get.length===0)
{
res.send(`Do not find product with name : ${req.params.id}`);
}
else{
res.json(get);
}
}
catch(err){
res.send(err);
}
});
app.listen(port_,'localhost',()=>{ console.log(`App run on port ${port_}`)});
when i enter following in address bar for insert data to mongo:
localhost:3000/insert?_id=36987&name=GLX&description=iranian smart phone
when use app.post(...) data does not post to mongo and app.get('/:name',async(req,res)
run. whenever use app.use('/insert',...) instead of app.post() data successfully posted to database.
What command should I use? What's my code problem?

Query using http post request

As I used app.get to query in urls as localhost:3000/data?country=Italy and I get the data stored in MongoDb. How can I use app.post request method to query the parameters and get the data? I'm unable to find the proper solution and I'm completely new to this.
const express = require("express");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const url = "mongodb://localhost:27017/source_scrapped_data";
const app = express();
mongoose.connect(url, { useNewUrlParser: true });
// mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log("Connected to mongo");
});
const covid_data = mongoose.model('Covid',
new Schema({}),
'covid_data');
app.get("/data", (req, res) => {
const continent = req.query.continent;
const country = req.query.country;
covid_data.find({'Continent':continent,'Country':country},(err,docs)=>{
if(err){
console.log(err)
res.send("no data found",err)
}
else{
console.log(err)
res.send(docs)
}
});
});
module.exports = app;
app.post("/data", (req, res) => {
const continent = req.body.continent;
const country = req.body.country;
covid_data.find({'Continent':continent,'Country':country},(err,docs)=>{
if(err){
console.log(err)
res.send("no data found",err)
}
else{
console.log(err)
res.send(docs)
}
});
});
This is how you can get data in post request that is passed in the body of the request.
This is not the standard practice you should not use post request to do get a query. Always use POST method to put some data in the database.

why does postman not recognize the "/:id" but instead throws an error?

i've managed to connect nodejs with postgresql. my problem is this, when trying to retrieve,delete or update a single item, the url '/v1/:id' is not recognized by postman.it throw a cannot get,or cannot delete or update error. but, retrieving all the user items works well. I'm not supposed to use any ORM but pure sql. I've also checked everywhere on the internet with no proper solution or explanation to this. What could be the issue?
//here is my app.js file
const express = require('express');
const bodyParser = require('body-parser');
const pg = require('pg');
const route = require('./routes/user');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use('/v1',route)
module.exports = app;
//here is my controller file that handles the logic
const db = require('../db/config');
const getAllUsers = (req,res,next)=> {
db.query('select * from users',(err,result)=>{
if(err) {
res.status(400).send('error in connection')
}
res.status(200).json(result.rows);
console.log('this is the getusers route ')
})
}
const getUserById = (req,res,next)=> {
const id =parseInt(req.params.id);
db.query('select * from users where id=$1',[id],(err,results)=>{
if(err) {
throw err
}
res.status(200).send(results.rows);
console.log('successfully found id');
})
}
//delete item
const removeItem = (req,res,next)=> {
const id = parseInt(req.params.id);
db.query('DELETE from users where id=$1',[id],function(err,result){
if(err) {
throw err
}
console.log('item deleted');
})
}
module.exports = {getAllUsers,getUserById,removeItem}
//and here is my route file that handles all the routes
const express = require('express');
const router = express.Router();
const controller = require('../controller/user');
router.get('/',controller.getAllUsers);
router.get('/users/:id',controller.getUserById);
router.delete('/item/:id',controller.removeItem);
module.exports = router;
:id should be treated as URL parameter
http://localhost:8000/v1/users/1234 -> where 1234 is your :id
I'm using POST on my test
id parameter is empty, please enter "id" here
From the screenshot of postman, seems like you missed to set the value for "id" under path variable.

How to correctly retrieve data using an node api of a sqlite3 database

I am coding a simple node.js application that retrieves store data from a sqlite3 database. I coded the API using express and when I test it with curl it doesn't retrieve the data.
I have tested the SQL model and it works.
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('********', (err) => {
if (err) {
return console.error(err.message);
}
console.log('Connected to the in-memory SQlite database.');
});
function recordNotFound(message) {
Error.call(this);
this.message = message;
this.status = 404;
}
var Users = function () {};
Users.prototype.getAll = function(callback) {
let sql = 'SELECT * FROM users';
db.all(sql, [], function(err, rows) {
if (err) {
console.log('chao1');
callback(err, null);
} else {
console.log('chao2');
callback(err, rows);
}
});
};
var users = new Users();
users.getAll(function(err, rows) {
console.log(rows);
callback(null, 1);
})
});
Also, when doing
SELECT * FROM users;
in the sqlite3 terminal it retrieves the information correctly.
However, in the file user_api_router.js I have,
var express = require('express');
userApiRouter = express.Router();
var Users = require('../model/users_sql_model')
var users = new Users();
userApiRouter.get('/', function(req, res) {
users.getAll(function(err, result) {
if (err) {
console.log('control1');
res.status(500).json({message: 'Error retrieving records!'});
return;
}
res.status(200).json(result);
});
});
And in the index.js file I have,
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
var usersApiRouter = require('./app/router/user_api_router');
app.use('/v1/user', usersApiRouter);
var port = 3000;
app.listen(port, function(){
console.log('listening on port ' + port);
});
When I run index.js and type
curl http://localhost:3000/v1/user
It says,
{"message":"Error retrieving records!"}
I don't know what to do to retrieve the records correctly using curl. Help me please!

Unable to check if field exists on MongoDB using NodeJs

I am using NodeJs and MongoDb as a backend service from my android app.I am checking if Phone field exists in my database.
My problem is everytime I check for the field it sends response field exists even if Phone field is not present in document.
Here is my code:
const express = require('express');
const bodyParser = require('body-parser');
const env = require('dotenv').config();
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
var dburl = process.env.URL;
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended:true}));
router.post('/checkPhone',(req,res) => {
var data = req.body.uId;
MongoClient.connect(dburl,{useNewUrlParser:true},(err,client) => {
if(err){
console.log("Error:" +err);
}
else{
var collect = client.db('Bookbudi_db').collection('Users');
collect.find({_id:data,Phone:{$exists:true}},(err,doc) => {
if(err){
console.log("Error:" +err);
}
if(doc){
res.send("Exist");
}
else{
res.send("Doesn't exist");
}
});
}
});
});
module.exports = router;
Someone please let me know what I am doing wrong in above code. Any help would be appreciated.
THANKS
if { $exists:true } returns the document - it means that the field is there.
It is possible that your schema defines this field and initiates it w/ null - note that $exists will still return those fields.
References:
$exists

Resources