I am working through the Developing Backbone.js Applications and I am trying to set up example2 which involves installing node.us with npm and Mongodb.
All seems to be installed properly, I can do some poking around mongodb with the mongo console, node.js is running fine, got my example server running and (seemingly) no errors on connecting to the mongodb:
//Connect to database
mongoose.connect( 'mongodb://localhost/library_database', function(err) { if (err)
console.log(err); } );
No errors... but on an attempt to post:
jQuery.post( '/api/books', {
'title': 'JavaScript the good parts',
'author': 'Douglas Crockford',
'releaseDate': new Date( 2008, 4, 1 ).getTime()
}, function(data, textStatus, jqXHR) {
console.log( 'Post response:' );
console.dir( data );
console.log( textStatus );
console.dir( jqXHR );
});
I'm getting a server 500 errors... no indication from the console or DB that anything was even attempted.
The get works fine, though there's nothing in the database, it comes back empty, but I can't get the post to work.
Can anyone suggest a process for debugging this? Is it possible my DB is configured read only?
Related
I am currently creating an API for a web scraping application to feed data from the web scraper into MongoDB. I have listed my code below that converts a .csv file to .json and then inserts it into MongoDB. The issue is, I have an index set up so that no two database entries are identical.
Whenever this occurs, it throws an error (as it should), but it stops the running of the server which is not good. Would I need to use a try/catch statement for this? How would I format this for a try/catch statement? I just need it to continue running even if the database entry throws an error. Thank you for the assistance!
csvtojson()
.fromFile("sample.csv")
.then(csvData => {
mongodb.connect(
url,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err, client) => {
if (err) throw err;
client
.db("databaseName")
.collection("collectionName")
.insertMany(csvData, options);
}
);
});
In trying to build my first express API, I am encountering many problems. I am following some simple guide on youtube, and his code works (FOR HIM). When I try it with Postman, I simply get nothing, but it appears to be in some kind of loop (because I handle the errors)
I have checked that my route is ok, and tried experimenting with next() (which seems like I don't need it just yet)
Player is my model made with Mongoose
app.get("/players/:id", (req, res) => {
const id = req.params.id;
Player.findById(id)
.exec()
.then(doc => {
console.log("From database", doc);
if (doc) {
res.status(200).json(doc);
} else {
res
.status(404)
.json({ message: "No valid entry found for provided ID" });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
});
So when trying a GET in Postman on:
http://localhost:3000/players/5cf66338f00c424494316eb2
I get a loading screen, and after some time "There was an error connecting to...".
Any help/tips/solution/insights are appreciated!
If your repo is up-to-date, then you are not connecting your app with your database.
Add the following code in your app replacing the database with your own database:
mongoose.connect('mongodb://localhost:27017/database', {useNewUrlParser: true});
I'm new with Couchbase and trying to use the couchbase module 1.2.1, the connection to the DB seems to work fine, but the get and getMulti operations are failing and the error I'm getting is "Operation timed out".
I tried to increase the timeout, but it didn't help.
var db = new couchbase.Connection({ host:'localhost:8091', bucket:'beer-sample'},
function(err){
if (err){
throw err; // not getting here
}
});
db.get("id", function(err, result) {
if (!err && result){ // getting error
req.id = result;
}
});
What can be the problem?
You should try to reinstall Couchbase Server and try again using a host of 127.0.0.1:8091.
What version of Couchbase Server, and what platform/architecture you are using would also be helpful to know.
I'm starting webapps development with Node, so I'm quite new with this technology.
I've done several examples and managed to make it run.
However, now I'm trying to use Mongodb but I'm not able to make it run properly. It seems that the connection is working but when I call the find() method and I go to localhost:3000/near (which is the url that makes the findAll docs), the browser spends about a half a minute loading and finishes returning nothing (ERR_EMPTY_RESPONSE).
This is my code:
app.js
app.get('/near', function(req, res){
server.findAll( function(error,docs){
res.render('near', {
title: 'Cerca tuyo!',
places:docs
});
})
});
And this my Server.js
//constructor
AppServer = function(host, port) {
this.db= new Db('node-mongo-places', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
//Devuelve la colección de "places"
AppServer.prototype.getCollection= function(callback) {
this.db.collection('places', function(error, places_collection) {
if( error ) callback(error);
else callback(null, places_collection);
});
};
//Devuelve todos los contenidos de la DB places
AppServer.prototype.findAll = function(callback) {
this.getCollection(function(error, places_collection) {
if( error ) callback(error)
else {
places_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
I have debugged the code writing console.log() and it seems that it does not reach to the callback function from places_collection.find().toArray(function(error, results) {
Any idea why the server does not return anything?
!!! EDIT:
I found some piece of code to test if the connection to mongodb is alright and it says that it's not: [Error: failed to connect to [localhost:27017]]
So the problem is in the connection. Should I run mongodb first? I thought that the app.js itself would did that for me!
Got the answer for this question:
As said, I thought that npm install mongodb would install the whole thing. However, it does not, so I managed to fix it by executing sudo apt-get install mongodb.
Once installed, the app itself runs mongodb.
I added this to my mongodb open() method so as I could see what was happening:
this.db.open(function(error,db){
if(error) {
console.log(error);
} else {
console.log("connected to mongod with no problems...");
}
});
I am learning and trying simple example using node.js and mongoskin. here is my function below
Problem following function is, if the mongodb server is disconnected then also I get the "err=null" hence not able catch connection error. If I restart node.js server (while mongoDB server is still disconnected) I get error as
"[Error: failed to connect to [server-aa070:27017]]"
// Process messages from client
app.post('/send', function(req, res){
var message = {
id: i++,
nickname: req.param('nickname', 'Anonymous'),
text: req.param('text', ''),
created_at: new Date()
};
conn.chat_log.insert(message, function(err) {
if(err!==null){
console.log(err);
}
else {
console.log(message);
console.log(err);
}
});
res.json({status: 'ok'});
});
I'm new to node.js and mongodb, but why are you using if(err!==null) rather than if(err)? If I'm understanding correctly, wouldn't this solve your problem?
Don't know about mongoskin, but for the node-mongo-native driver (the driver that mongoskin is built on), the author said:
Note that there's no reason to pass a callback to the insert or update
commands unless you use the safe:true option. If you don't specify
safe:true, then your callback will be called immediately.