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
Related
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?
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
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.
I am using this code:
app.post("/users", function(req, res) {
db.collection(USERS_COLLECTION).insertOne(req.body , function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new user.");
} else {
res.status(201).json(req.body);
}
});
});
and I am trying putting in this request: localhost:8080/users?firstName=foo&lastName=bar
but when I try the post request in postman it returns just an id and doesn't insert the params in the database.
{
"_id": "584f04eb141faa7df7fc4059"
}
how do I fix this so that it returns the data or do I need to create a schema first and check against it? If I could be pointed in the right direction that would be great
You're correct in that you need a schema!
If there were no schema in a database, you essentially would have a bucket full of (potentially) mismatched JSON objects. Thus, it would be tedious to ensure that your keys match up to their expected values.
If you're new to Mongo, I'd recommend checking out Mongoose ODM. It helps when trying to understand the structure and quirks of a NoSQL DB.
ok.. So I created a Schema
var mongoose = require('mongoose');
// user schema
var usersSchema = mongoose.Schema({
firstName: String,
lastName : String,
email : String
});
mongoose.model('users', usersSchema);
and the post request code looks like this:
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var mongodb = require("mongodb");
var ObjectID = mongodb.ObjectID;
var USERS_COLLECTION = "users";
var mongoURL = "the url is here";
var user = require("./Models/User");
var mongoose = require('mongoose');
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
mongoose.connect(mongoURL);
// USERS API ROUTES BELOW
// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
/* "/USERS"
* POST: creates a new user
*/
app.post("/users", function(req, res) {
var firstName = req.params.firstName;
var lastName = req.params.lastName;
var email = req.params.email;
//call the create function for our database
mongoose.model('users').create({
firstName : firstName,
lastName : lastName,
email : email
}, function (err, user) {
if (err) {
res.send("There was a problem adding the information to the database.");
} else {
//User has been created
console.log('POST creating new users: ' + user + firstName);
res.format({
//JSON response will show the newly created user
json: function(){
res.json(user);
}
});
}
})
});
though the issue is that when I send a http post request :
localhost:8080/users?firstName=foo&lastName=bar&email=foobar#gmail.com
req.body.firstName = undefined and req.params.firstName = undefined how do I get it to properly read in the values? When I put static strings in the place of req.body... it works perfect.
this is what returns in json currently:
{
"__v": 0,
"_id": "5851567048018fa141543f53"
}
21 things matter the most on this problem
you do not implement a body-parser
here you can install it by: npm I body-parser
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
add content type in postman if you use postman to send API
Content-Type: application/JSON
I have a list of url params that I'm using with express.
Now I'm trying to put this in an external file so they can be used though-out the whole app, the param works when it's in the file but not when it's external.
I looked though the documentation but it lacks anything about catching all params.
The main app that has many different API routes.
var routeParams = require('./route_params.js');
app.param(routeParams);
The params file that needs to be used globally though-out the app.
var express = require('express');
var router = express.Router();
require('./models/User');
var mongoose = require('mongoose');
var User = mongoose.model('User');
//UserId param.
router.param('userid', function(req, res, next, id)
{
var query = User.findById(id);
query.exec(function (err, user)
{
if(err)
{
res.json(err);
}
else if(!user)
{
res.json({message:'User does not exist'});
}
else
{
req.userid = user;
return next();
}
});
});
module.exports = router;