model.save() returns an invalid output - javascript

I am making a simple test for RESTApi using Node.js, mongodb and express from this article:
MERN Part I: Building RESTful APIs with Node.js and Express
but there is an error somewhere in code i can't locate. The author of article used babel but due to some other error i avoided it. Given below are code files:
App.js
var routes= require('./src/routes/userRoutes').routes
var express= require("express")
var mongoose=require('mongoose')
var bodyParser=require('body-parser')
const app = express();
const PORT=4001
// SET INDEX PAGE
app.get('/',function(req,res){
res.send(`Node and express server running on PORT ${PORT}`);
});
// START SERVER
app.listen(PORT,function(){
console.log(`Your server is running on PORT ${PORT}`);
});
// ESTABLISH ROUTES
routes(app)
// Join Database to API
mongoose.Promise= global.Promise;
mongoose.connect('mongodb://localhost/userdb', {
useNewUrlParser:true,
useUnifiedTopology:true
})
// body-parser setup
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
userModel.js : I have commented out the "required" to avoid the Validation Error and see what document is being saved in the collection.
var mongoose = require('mongoose')
const Schema = mongoose.Schema;
const UserSchema = new Schema({
userName:{
type:String,
//required:"Enter your name",
},
UserID:{
type:Number,
//required:"Enter User ID:",
},
password:{
type:String,
// reequired:"Enter your password?",
}
});
module.exports={UserSchema}
userController.js:
var mongoose=require('mongoose')
var UserSchema = require("../models/userModel").UserSchema;
const UserModel= mongoose.model("Users",UserSchema)
const addNewUser = (req,res) => {
let newUser= new UserModel(req.body);
newUser.save((err,user) => {
if(err) res.send(err)
else res.json(user)
})
}
module.exports={addNewUser}
userRoute.js:
var addNewUser = require('../controllers/userController').addNewUser;
const routes = (app) => {
// create routes for login/signup/view
app.route('/users')
.get((req,res)=> res.send("Get request successful"))
app.route('/users/:userID')
.put((req,res)=>res.send(`Put Request succesful for ${req.params.donationID}`))
.delete((req,res)=>res.send("delete Request successful"))
.post(addNewUser);
app.route('/done')
.get((req,res)=>{
res.send("Goodbye");
process.exit(0);
});
}
module.exports={routes};
Response recieved when POST request with URI:localhost:4001/users/1?userName=Adnan&UserID=123&password=0000
{
"_id": "5fd0b07b12615110d420a91b",
"__v": 0
}
Expected Output: User Object in JSON

Related

Mongodb connected on nodejs and localhost keeps on reloading

I am trying to connect to my backend mongodb 5.0.5 with nodejs express script.
when running the app.js using nodemon it shows your mongodb is connected but on the localhost it keeps on reloading without any error stack trace.
I am using mongoose models in the models as in MVC in nodejs. Not sure why its is not getting run on localhost, it was working fine when last I used these files.
here are my files:
app.js
// imports
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const { append } = require('express/lib/response')
const zomatoRoutes = require('./Routes/zomato')
const mongoose = require('mongoose')
// create express server
var app = express()
//listen to a port
app.listen(7878, () => {
console.log('app running on port 7878');
})
app.use(bodyParser.json())
//connect mongodb
mongoose.connect('mongodb://localhost/zomato', () => {
console.log("MongoDB Connected");},
e => console.log(e)
)
// Middleware routes
app.use('/zomato', zomatoRoutes)
app.use(cors())
Model > locations.js
const mongoose = require('mongoose')
const locationSchema = new mongoose.Schema({
name: {
type: String,
required:true
},
city_id: {
type: String,
required:true
},
location_id: {
type: String,
required:true
},
country_name: {
type: String,
required:true
}
})
module.exports = mongoose.model("LocationsModel", locationSchema, "locations")
Controllers > location.js
const { status } = require('express/lib/response')
const Locations = require('../Model/location')
exports.getAllLocations = (req, res) => {
Locations.find().then(
result => {
res.status(200).json({ message: "data fetched successfully", data: result })
}
).catch(error => {
res.send(500).json({ message: "Error in Database", error: error })
})
}
and my routes
zomato.js
const express = require('express')
const Router = express.Router();
const RestaurantController = require('../Controller/Restaurant')
const LocationsController = require('../Controller/Location')
// configure routes
// Restaurants routes
Router.get('/restaurants', RestaurantController.getAllRestaurants)
Router.post('/restaurants/filter/:pageNo', RestaurantController.getRestaurantsByFilter)
// Locations routes
Router.get('/locations', LocationsController.getAllLocations)
module.exports = Router
my Json files
locations.json goes like this:
[
{
"_id": "1",
"name": "ShalimarBhagh, Delhi",
"city_id": "1",
"location_id": "1",
"country_name": "India"
},
{
"_id": "2",
"name": "Janpat, Delhi",
"city_id": "1",
"location_id": "2",
"country_name": "India"
},
{
"_id": "3",
"name": "MSP, Delhi",
"city_id": "1",
"location_id": "3",
"country_name": "India"
}
]
** Updates: I forgot to mention I recently updated to windows10 to make sure my react app works and after this issue is arising, now I created a fresh application with removing mongo and re-installing mongodb still gets me this error in postman Error: read ECONNRESET**
Update I get this stack trace
C:\Users\acer\Documents\EDUREKA\Nodejs-mongodb-
mongoose\node_modules\mongoose\lib\connection.js:797
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri
(C:\Users\acer\Documents\EDUREKA\Nodejs-mongodb-
umongoose\node_modules\mongoose\lib\connection.js:797:32)
Try this instead:
// imports
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const { append } = require('express/lib/response')
const zomatoRoutes = require('./Routes/zomato')
const mongoose = require('mongoose')
// create express server
const app = express()
// Middleware routes
app.use(cors())
app.use(bodyParser.json())
app.use('/zomato', zomatoRoutes)
//connect mongodb
mongoose.connect('mongodb://localhost/zomato', () => {
console.log("MongoDB Connected");
const server = app.listen(7878, () => {
console.log('app running on port 7878');
})
server.setTimeout(0) // disable the default time out server mechanism
},
e => console.log(e)
)
Which is:
initialize exprress app
register middlewares
connect to mongo
if connection successful (and only then) - start the application
Also, replace your code
res.status(200).json({ data: 'whatever' })
to:
res.status(200).send({ data: 'whatever' })
There is a chance that your response is not getting back to client, hence - resulting in timeout error. This approach should fix this as well
Hope it will help you with your problem
Localhost is not resolved, though I changed my mongodb to ipv6 using mongod --ipv6 still it does not accept and in stack trace shows isIPV6 : false.
so finally I had to change the using the answer here listen to port using ipv4
//connect to mongoDB
const uri = 'mongodb://localhost:27017/zomato';
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
family:4
}
const connectWithDB = () => {
mongoose.connect(uri, options, (err, db) => {
if (err) console.error(err);
else console.log("database connection")
})
}
connectWithDB()
It is working now and fetching data but want to resolve the issue of ipv6 nodejs.

In Postman GET working fine but POST method keeps on sending request. Using Mongoose, Javascript

PROBLEM: When I am making the POST request in postman, the postman keeps on sending requests and I do not get any response.
I went through other answers about postman hanging when POST request is made, but could not find a solution to my problem.
GET REQUEST WORKING FINE
Following is the request that I made
{
"title": "This is title",
"description":"This is my first RestfulAPI"
}
I have 3 files Post.js, posts.js, app.js
Post.js
const mongoose = require('mongoose');
//Creating a schema
const PostSchema= mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
}
})
module.exports=mongoose.model('Posts',PostSchema);
posts.js
const express= require('express');
const router=express.Router();
const Post= require('../models/Post');
router.get('/',(req,res) => {
res.send('We are on posts');
});
router.get('/specific',(req,res) => {
res.send('Specific posts');
});
router.post('/',async (req,res)=>{
console.log(req.body);
const post= new Post({
title: req.body.title,
description: req.body.description
});
try{
const savedPost = await post.save();
res.json(savedPost).status(3000).end();
}catch(err){
res.json({message: err}).status(3000).end();
console.log('Something is wrong');
}
});
module.exports= router;
app.js
const express = require('express');
const mongoose= require('mongoose');
const app= express();
const bodyParser= require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
const postsRoute = require('./routes/posts');
app.use('/posts',postsRoute);
app.get('/',(req,res) => {
res.send('We are on home');
});
mongoose.connect(process.env.DB_CONNECTION,{ useNewUrlParser: true,useUnifiedTopology: true },() =>
console.log('connected to DB!')
);
app.listen(3000);
My console after sending POST request
You would not need .end() after calling res.json(), as you probably want to send the savedPost back to the client.
The express documentation mentions here that
[res.end()] is used to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().
You also need to send back the proper HTTP code that ranges from 1xx to 5xx, when working with HTTP. You can read more about them here
Your response should probably look like
res.status(200).json(savedPost);

Node and DialogFlow Error: UnhandledPromiseRejectionWarning: TypeError: sessionClient.projectAgentSessionPath is not a function

I'm trying to connect from Nodejs to DialogFlow. I have completed all the steps to configure the user agent, the intent, etc. If I lunch with NODEMON the app, all its ok, but when I send a GET or POST request I get this error:
"UnhandledPromiseRejectionWarning: TypeError: sessionClient.projectAgentSessionPath" and more. But I think the most relevant mistake is this.
The code I used it's the same as the APi docs. I don't know why I get this error.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const dialogflow = require('#google-cloud/dialogflow');
const uuid = require('uuid');
//const sendReq = require('./reqDialogFlow');
async function runSample(projectId = 'helpcenter-qwoj') {
// A unique identifier for the given session
const sessionId = uuid.v4();
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);
console.log(sessionPath);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: 'hello',
// The language used by the client (en-US)
languageCode: 'it',
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
};
app.get('/', (req, res) => {
res.send({ "hello": "Daniele Asteggiante" })
});
app.post('/api/textAPIE', (req, res) => {
res.send({ "text": "CIAO" });
runSample();
});
app.use(bodyParser.json());
const PORT = process.env.PORT || 5000;
app.listen(PORT);
i had the same error.
i had installed
npm i dialogflow
instead of
npm install #google-cloud/dialogflow
I tried to change the Express Version version with an earlier version 4.17.0 instead 4.17.1.
Now it goes.
change "sessionClient.projectAgentSessionPath" -> "sessionClient.sessionPath"
Found this solution on github:https://github.com/googleapis/nodejs-dialogflow/issues/127

Can two servers access a common mongoDB database

I have 2 webservers that I have created on ports 3000 and 4000.
One of the webservers created a database and has 3 collections..
show dbs
local 0.000GB
sensor_db 0.000GB
use sensor_db
switched to db sensor_db
show collections
sensors
templategroups
templates
Can the 2nd server access this Database created ? if yes, I am not able to access the collections ..Is there any syntax to it?
1st server:
var express = require('express');
var app= express();
var path = require('path');
var bodyParser= require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sensor_db');
var Schema = mongoose.Schema;
var sensorSchema = new Schema({
value:{ type:Number, default:0},
format:{type:String, default:"default"},
id:{type:Number,required:true,unique:true},
description:{type:String},
type:{type:String},
groupId:{type:Number},
users:{type:Array,default:[]},
admin:{type:String,default:'Undefined'},
status:{type:String,default:'Undefined'},
owner:{type:String,default:'Undefined'},
templateId:{type:Number}
});
var Sensor = mongoose.model('Sensor',sensorSchema);
app.get('/sensorlist',function(req,res) {
console.log("I recieved a GET /sensorlist request");
Sensor.find(function(err,data){
if (err) return console.error(err);
console.log(data);
res.json(data)
});
});
app.post('/check/health',function(req,res){
socket.emit('data', 'I need your health status', function ack(data) {
console.log('data emit was acknowledged by Monitoring Server:', data);
return res.json(data);
});
});
2nd Server:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var express = require('express');
io.on('connection', function(socket){
console.log('connection received from Provisioning');
// To get messages from Provisioning server
socket.on('data', function(data, ack) {
console.log('Message from provision is : ' + ': ' + data);
ack('here is your data - 1111');
console.log("Trying to access the Sensor_DB Database");
Sensor.find(function(err,data){
if(err) return console.error(err);
console.log(data);
//res.json(data);
});
});
});
server.listen(4000, function(){
console.log('socket.io server listening on *:4000');
});
I get error - Sensor is not defined
Much Thanks
Jessi
I tried to dispay the collections once its connected to the DB but get this error message : Cannot read property 'hasListCollectionsCommand' of null
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/sensor_db') ;
console.log("successfully connected to the database");
//mongoose.connection.db
mongoose.connection.db.listCollections().toArray(function(err, names) {
if (err) {
console.log(err);
}
else {
names.forEach(function(e,i,a) {
mongoose.connection.db.dropCollection(e.name);
console.log("--->>", e.name);
});
}
});
Two Different servers cannot share the same instance of the sensor object.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sensor_db');
var Schema = mongoose.Schema;
var sensorSchema = new Schema({
value:{ type:Number, default:0},
format:{type:String, default:"default"},
id:{type:Number,required:true,unique:true},
description:{type:String},
type:{type:String},
groupId:{type:Number},
users:{type:Array,default:[]},
admin:{type:String,default:'Undefined'},
status:{type:String,default:'Undefined'},
owner:{type:String,default:'Undefined'},
templateId:{type:Number}
});
var Sensor = mongoose.model('Sensor',sensorSchema);
This code declaring the schema for one server not for the second . so you have to declare the instance in the second server also.
Issue not with the mongo data base issue is the sensor instance that is not have any declaration in second server.

Moongose, expressjs and node-webkit

I'm building an app using node-webkit, based on expressjs and mongoose. I'm new to basically all of this.
I've got a mongoDb hosted online and i'm try to use it in my app, but i'm missing something
I created in model folder db.js, where i connect with the db
var mongoose = require('mongoose');
mongoose.connect('mongodb://user:password#ds012345.mlab.com:port/mydb') //this isn't the real link
then my model, clients.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var clientSchema = new Schema ({
name: String,
//other fields
});
var client = mongoose.model('client', clientSchema);
module.exports = client;
Then, in my app.js
var db = require('./model/db')
I'm also using routes, so in my index.js i got
var client = require('../model/clients')
But i cannot use any function (save, find, ecc.), i can just create models.
I think I'm not connecting in the right way all the modules, i was previously using diskdb and i connected to it in my index.js, but i tried in the same way and it doesn't work anyway.
Also, when i build the app, my mongoose connection status is 2.
Here are a few things:
what is ecc? you should connect to something like this: mongoose.connect('mongodb://localhost:27017/test');
27017 is the default port for MongoDB and test is the name of your database. Also make sure you start mongo server with mongod then run mongo console mongo.
Your field should specify type of the data:
var clientSchema = new Schema ({
name: String,
age: Number
});
So you want to save the document into database:
var client = mongoose.model('client', clientSchema);
var data = {
nome: 'something'
};
var user = new client(data);
user.save(function(err) {
if(err) console.log(err);
});
In your route, you can do something like this to query back and send data back to the req:
var express = require('express');
var router = express.Router();
var clientSchema = require('../models/clientSchema');
router.get('/', function(req, res, next) {
UserSchema.find({} , function(err, data) {
if (err) console.log(err);
res.render('index', {
data: data
});
});
});
module.exports = router;
Hope this help!

Categories