I am trying to run my .js script in node but while adding some new data in database the server is not loading and giving this error(CastError: Cast to string failed for value). I am not getting the error can someone please help me out?Attaching the SS of cmd and the code as well![enter image description here][1]
Code is as follows:
var express=require("express");
var app= express();
var bodyParser=require("body-parser");
app.use(bodyParser.urlencoded({extended:true}));
app.set("view engine","ejs");
var mongoose=require("mongoose");
mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology",true);
mongoose.connect("mongodb://localhost/yelp_camp");
var campgroundsschema= new mongoose.Schema({
name:String,
image:String
});
var Campground= mongoose.model("Campground",campgroundsschema);
//Campground.create(
// {
// name:"Granite Hill",
//image:"https://images.unsplash.com/photo-1487750404521-0bc4682c48c5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"
//},function(err,campgrounds){
//if(err){
// console.log(err);
//}
//else{
// console.log("We have created a new campground");
// console.log(campgrounds);
//}
//}
//)
app.get("/",function(req,res){
res.render("landing");
});
app.get("/campgrounds",function(req,res){
Campground.find({},function(err,allCampgrounds){
if(err){
console.log(err);
}
else{
res.render("campgrounds",{campgrounds:allCampgrounds});
}
});
});
app.post("/campgrounds",function(req,res){
var name=req.body.name;
var image=req.body.image;
var newCampground={name: name,image: image};
Campground.create(newCampground,function(err,newlyCreated){
if(err){
console.log(err);
}
else{
console.log("we have created a new campground here!!");
res.redirect("/campgrounds");
}
});
});
app.get("/campgrounds/new",function(req,res){
res.render("newcamp.ejs");
});
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log('Example app listening on port ' + port + '!');
});
Error ScreenShot: [1]: https://i.stack.imgur.com/9vNPz.png
( please open this link to view the image)
Looking at the image link that you attached in the body. I can see that you are sending an array of string which apparently looks like this
[ "C1", "A URL" ]
which is actually an array data type, whereas the type that you have set in your schema for name is String.
If you want to save an array of strings? You must change the data type to Array of strings i.e.
name: [String]
or you can stringify the array that you are sending. Using
JSON.stringify(yourArray)
This is the url to data types of mongoose so you can explore other data types as well.
UPDATE
var image = JSON.stringify(req.body.image);
In the above chunk of code i stringified the array of images. And then I tried to save it and its working.
Related
I was familiar with MongodB for CRUD operation. Here, I'm trying to make simple post request on mongodB atlas but I want to know where I have done error for the connection and posting data to MongodB atlas.
Model.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let quizSchema = new Schema({
title: {
type: String,
},
description: {
type: Number,
},
question: {
type: String,
},
});
const Quiz = mongoose.model("Quiz", quizSchema);
module.exports = Quiz;
index.js
I'm trying to create the database collection name "QuizDatabase" and insert the data to it.
var express = require("express");
var bodyParser = require("body-parser");
const Quiz = require("./views/model/model");
var Request = require("request");
var app = express();
app.use(bodyParser.json());
const MongoClient = require("mongodb").MongoClient;
const uri =
"mongodb+srv://username:password#cluster0.iom1t.mongodb.net/QuizDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connect(uri);
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.post("/new/", function (req, res) {
Quiz.collection("QuizDatabase").insertMany(req.body, function (err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new quiz.");
} else {
res.status(201).send(JSON.stringify(body));
}
});
});
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({ error: message });
}
You dont have to use mongo client if you are already using mongoose.
In index.js file just import the model
const Quiz = require("./model");
And you are already using mongoose to connect to db when you write mongoose.connect(uri); You don't have to use client.connect() again.
Query to insert -
Quiz.insertMany(req.body);
Your index file should look like this -
const Quiz = require("./views/model/model");
var Request = require("request");
var app = express();
app.use(bodyParser.json());
const uri =
"mongodb+srv://username:password#cluster0.iom1t.mongodb.net/QuizDatabase?retryWrites=true&w=majority";
mongoose.connect(uri);
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.post("/new/", function (req, res) {
Quiz.insertMany(req.body, function (err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new quiz.");
} else {
res.status(201).send(JSON.stringify(body));
}
});
});
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({ error: message });
}
There are several reasons.
Connection Issues to the MongoDB database.
To check this insert app.listen() into mongoose connect. This would make sure you can only run development on your preferred PORT only when it has successfully connected to your Database. e.g From your code
mongoose.connect(uri)
.then(() => {
//listen for PORT request
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
}).catch((error) => {
console.log(error);
});
Try purposely using the wrong Username or Password and see if you get this error:
MongoServerError: bad auth : Authentication failed.
at Connection.onMessage (/Users/user/Documents/..<pathway>../connection.js:207:30)
*
*
*
*
ok: 0,
code: 8000,
codeName: 'AtlasError',
[Symbol(errorLabels)]: Set(1) { 'HandshakeError' } }
If you don't get this error then you have a connection problem. To solve this, I added my current IP ADDRESS and 0.0.0.0/0 (includes your current IP address) at the Network Access page. So you click on MY CURRENT IP ADDRESS and confirm upon setting up the network. Go to NETWORK ACCESS, click on add new IP ADDRESS, input 0.0.0.0/0 and confirm. Then try using the wrong username or password in the URI link given to you to see if it gives the above-expected error, then you can now correct the Username and Password, and npm run dev or npm start (However you configured it in your package.json file).
Code issues
First of I would correct your Model.js file from this:
const Quiz = mongoose.model("Quiz", quizSchema);
module.exports = Quiz;
to this:
module.exports = mongoose.model("Quiz", quizSchema);
I can see why yours can work, but it may be an issue as you want to get the schema upon accessing the whole file.
Secondly, I would correct the code for Posting and you can do that in 2 ways using the asynchronous method. Which depends on the method of assigning the req.body.
Way 1:
app.post("/new/", async (req, res) => {
const { title, description, question } = req.body;
//adds doc to db
try {
const quiz = await Quiz.create({ title, description, question });
res.status(200).json(quiz);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
OR
Way2:
app.post("/new/", async (req, res) => {
const quiz = new Quiz(req.body);
//adds doc to db
try {
const savePost = await quiz.save();
response.status(200).send(savePost);
} catch (error) {
response.status(400).send(error);
}
});
NOTE: You don't necessarily have to create a named database and collection in Mongo Atlas before starting the project. The URI given to you covers that if there are no problems with the connection to the DB or the Code.
based on your code
URI:
"mongodb+srv://username:password#cluster0.iom1t.mongodb.net/QuizDatabase?retryWrites=true&w=majority";
would create a database called: QuizDatabase and collection called: quizs (MongoDb always creates the plural word from the model given and makes it start with lowercase (i.e from your Model.js, the mongoose.model("Quiz"))).
If no database is named in your URI, then a database called test is automatically created for you as a default database, with the collection name being the mongoose.model("") given.
CONCLUSION
This should solve at least 90% of your issues, any other creation/POST problems is currently beyond my current expertise. Happy Coding 🚀🚀🚀
I am using Cloude 9 environment for developing my nodejs app. In that I have written code to connect to mongodb database. I am successfully connecting to database and adding record to collection.
Now I want to send the collection info in return. But using res.send(collectionInfo); is not working.
Let me know how should I achieve this
Below is the code of my server.js file
var Db = require('mongodb').Db;
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var ejs = require('ejs');
var app = express();
var helpers = require('express-helpers')
var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;
var db;
helpers(app);
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded
var server = http.Server(app);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function () {
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//app.use(express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, '/client')));
// MongoDB Connection
app.use(function(req, res, next) {
next();
})
app.get('/monogdb', function (req, res) {
res.render('monogdb.ejs');
});
app.post('/ajax-mongo-connect', function (req, res) {
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
if(err){
console.log(err);
}else{
var db = mongoClient.db("mydb");
db.createCollection("students", { name : req.body.nm, description : req.body.desc, location : req.body.loc } );
console.log('database connected',db);
var collectionInfo = db.collection("students");
mongoClient.close();
//res.setHeader('Content-Type', 'application/json');
res.send(collectionInfo);
}
})
})
As per #Roman Sachenko answer, I have tried to use
res.send(collectionInfo.toJSON()); but it is giving below error
/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:299
throw err;
^
TypeError: Object #<Collection> has no method 'toJSON'
at /home/ubuntu/workspace/server.js:66:41
at MongoClient.open
(/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/mongo_client.js:103:5)
at Db.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:296:11)
at process._tickCallback (node.js:442:13)
and using res.send({data: collectionInfo}); gives error
home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:299
throw err;
^
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at ServerResponse.res.json (/home/ubuntu/workspace/node_modules/express/lib/response.js:185:19)
at ServerResponse.res.send (/home/ubuntu/workspace/node_modules/express/lib/response.js:117:21)
at /home/ubuntu/workspace/server.js:67:21
at MongoClient.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/mongo_client.js:103:5)
at Db.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:296:11)
at process._tickCallback (node.js:442:13)
Try to return this: res.status(200).json({'myCollection' : collectionInfo});.
You can find more details about express response here
Update:
After you explain the details, take a look at the code below:
app.post('/ajax-mongo-connect', function (req, res) {
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
if(err){
console.log(err);
res.status(500).json({message : 'OMG, an error occurred'});
}else{
var db = mongoClient.db("mydb");
db.createCollection("students", { name : req.body.nm, description : req.body.desc, location : req.body.loc } );
console.log('database connected',db);
var collectionInfo = db.collection("students");
// Here we will find all students
collectionInfo.find({}).toArray(function(err, students) {
// so now, we can return all students to the screen.
res.status(200).json({'myCollection' : students});
}
}
})
})
Cheers!
Mongoose ODM
First of all I would like to recommend you using Mongoose ODM:
https://github.com/Automattic/mongoose
So you will make you work with database much easier.
Basically it returns (Mongoose) normal object as results, but in case of issues you may try to use toObject() or toJSON() or as it mentioned create own object like {data: mongoCollection}
Examples:
res.send(collectionInfo.toObject());
res.send(collectionInfo.toJSON());
res.send({data: collectionInfo});
Please refer to the link in case of questions:
http://mongoosejs.com/docs/guide.html#toJSON
Native Driver
As for native driver, it also should return normally-constructed object, but according to issues I faced with in the past, JSON.stringify always helps if you set headers manually.
You may also check the contents of your entity. So you can just output it by console.log(collectionInfo);
Then just make sure that there is correct object inside.
And according to results you can take actions like:
res.send(JSON.stringify(collectionInfo)) //set headers manually
res.json(JSON.stringify(collectionInfo)) //you don't need to set headers
At least you will know what exactly is inside of collectionInfo. I think it will be enough to investigate the issue.
You can view circular JSON objects by doing this in node.js:
const util = require('util') // Native node module
util.inspect(circularObj)
You can call it from anywhere in the code, so it's very versatile.
I have a simple code that gives a JSON response for a specific route. Here's my current code:
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: '****',
password: "****",
database: 'restaurants'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 1235);
app.use(express.static(__dirname + '/public/images'));
app.get('/DescriptionSortedRating/',function(request,response){
var name_of_restaurants;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM restaurants ORDER BY restaurantRATING', function(err, rows, fields)
{
console.log('Connection result error '+err);
name_of_restaurants = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'restaurants' : name_of_restaurants
});
} );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
How can I make an XML response equivalent to the JSON above?
You can use any number of the XML libraries available on npm. Here's an example using the simply-named "xml" library:
var xml = require('xml');
response.set('Content-Type', 'text/xml');
response.send(xml(name_of_restaurants));
See the module's documentation for a description of how it converts JavaScript objects to XML. If you need things returned in a specific XML format, you'll have more work to do, of course.
As an update to this, it looks like res.type should be used instead as res.set does not give the same results.
res.type('application/xml');
More information can be found in the API reference.
How to decode the param values received which were received as Base64 encoded form and insert into database ?
This is what i have tried.
According to this i am getting one value recieved from the client as
param value and inserting into server ( I have recieved the request
at POST )
No base64 encoding is done here
I am using this code at present :
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: '******',
password: "******",
database: 'posting_information_DB'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 1234);
app.use(express.static(__dirname + '/public/images'));
app.post('/Name/',function(request,response,next){
app.use(express.bodyParser());
var keyName=request.query.Key;
var name_of_restaurants;
async.series( [
function(callback) {
connection.query('INSERT INTO details (name) VALUES (?)', [keyName], function (err, rows, fields)
{
console.log('Connection result error ' + err);
callback();
});
}
// Send the response
] );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
What i am trying to do !
Now what changes should i need to make so that when i need recieve a
image and string as two param values
These values are Base64 encoded
How to decode these Base64 here and then insert the retrieved param
values to database
How to modify my posted Express code !
Thanks !
You can retrieve the image parameter using request.params and then create a Buffer object, specify the base64 encoding and then convert it using the .toString() method.
app.post('/Name/', function(request, response, next){
var image = new Buffer(request.params.image, 'base64').toString('binary');
// do the database insert...
});
I'm using Express.js and MongoLab and I followed the Heroku setup to get MongoDB working in production throwing this code in my app.js.
//Mongo on Heroku Setup
var mongo = require('mongodb');
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/mydb';
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('mydocs', function(er, collection) {
collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {
});
});
});
and I have the following routes and field for my email form (also in app.js):
//Routes
app.get('/', function(req, res) {
res.render('index', {
title: 'DumbyApp'
});
});
//save new email
app.post('/', function(req, res){
emailProvider.save({
address: req.param('address')
}, function( error, docs) {
res.redirect('/')
});
});
This renders the new form on the index page and lets me save it locally but not in production because I don't know how to setup my email collection. Can anyone walk me through this? brand new to using MongoDB and Node.js, so could use some help.
EDIT:
In The MongoLab Database Interface, I made a collection called emails. Is this the right course of action?
EDIT 2:
Here's defining EmailProvider in app.js along with the file itself.
app.js
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, EmailProvider = require('./emailprovider').EmailProvider;
var emailProvider= new EmailProvider('localhost', 27017);
emailprovider.js
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
EmailProvider = function(host, port) {
this.db= new Db('localdb', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
EmailProvider.prototype.getCollection= function(callback) {
this.db.collection('emails', function(error, email_collection) {
if( error ) callback(error);
else callback(null, email_collection);
});
};
//save new email
EmailProvider.prototype.save = function(emails, callback) {
this.getCollection(function(error, email_collection) {
if( error ) callback(error)
else {
if( typeof(emails.address)=="undefined")
emails = [emails];
for( var i =0;i< emails.address;i++ ) {
email = emails[i];
email.created_at = new Date();
}
email_collection.insert(emails, function() {
callback(null, emails);
});
}
});
};
exports.EmailProvider = EmailProvider;
While the connection code in the first code box appears to be correct, the emailProvider object isn't using it. Instead, in app.js, the EmailProvider is being connected to localhost:27017 and the database name is hardcoded in emailprovider.js as 'localdb'.
What you want to do instead is use the connection information provided in the MONGOLAB_URI environment variable in your EmailProvider, which contains the host, port, and database name already.
There are a number of ways to go about doing this, but one way would be to move your connection code from that first code box into the EmailProvider constructor, and then change the constructor so that it takes a URI instead of a host and port. That way, you can pass the MONGOLAB_URI variable to the constructor in app.js.