How to connect to mongoLab? - mongodb

I developed a simple MEAN stack CRUD app. I deployed my site to azure websites. In my localhost the app work fine. But I want to connect with mongoLab database. How can I connect it?
This is the code for server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('posts', ['posts']);
var bobyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bobyParser.json());//
app.get('/posts', function (req, res) {
console.log("I got the server request!")
db.posts.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.post('/posts', function (req, res) {
console.log(req.body);
//Insert - This is the first part of the CRUD
db.posts.insert(req.body, function (err, doc) {
res.json(doc);
});
});
app.delete('/posts/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.posts.remove({ _id: mongojs.ObjectId(id) }, function (err, doc) {
res.json(doc);
});
});
app.get('/posts/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.posts.findOne({ _id: mongojs.ObjectId(id) }, function (err, doc) {
res.json(doc);
});
});
app.put('/posts/:id', function (req, res) {
var id = req.params.id;
console.log(req.body.name);
db.posts.findAndModify({
query: { _id: mongojs.ObjectId(id) },
update: { $set: { name: req.body.name, info: req.body.info, twitter: req.body.twitter }},
new: true
}, function (err, doc) {
res.json(doc);
});
});
app.listen(3000);
console.log("Server running from port 3000");
How can I make the connection? I have the connection info what azure provides.
Thanks a lot.

Can you look at the exact Exception error message?
Try something like the following:
try
{
smtp.Send(msg);
Response.Write("<script>alert('Mensaje enviado correctamente');</script>");
NullTextBox();
}
catch (Exception ex)
{
Response.Write(string.Format("<script>alert('There is an error on connection to DB on microsoft azure:{0}');</script>", ex.ToString()));
NullTextBox();
}

Related

Postman sending request hanging

I am new to Postman. I am unsure of why my postman is hanging when trying to get from "http://localhost:8001/application/cards". It's supposed to respond with an empty array but it just keeps sending request. It works for "http://localhost:8001" to which it does give me "Hello World!" but doesn't work when I add /application/cards. Is there new syntax update? I can give more information about my code if necessary.
...
const app = express();
const port = process.env.PORT || 8001;
...
app.use(express.json());
app.use(Cors());
mongoose.connect(connection_url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
app.get('/', (req, res) => res.status(200).send('Hello World!'));
app.post('/application/cards', (req, res) => {
const dbapplication = req.body;
Cards.create(dbapplication, (err, data) => {
if (err)
{
res.status(500).send(err);
}
else
{
res.status(201).send(data);
}
});
});
app.get('/application/cards', (req, res) => {
Cards.find((err, data) => {
if (err)
{
res.status(500).send(err);
}
else
{
res.status(200).send(data);
}
});
});
Note: /application/cards in my question was an example, but SpartanSwipe is actually my application.
Upon testing data using POST http://localhost:8001/application/cards, I got a 500 Internal Server Error after about 10 seconds.
[
{
"name": "Test Name",
"profPic": "https://as1.ftcdn.net/v2/jpg/01/17/42/38/500_F_117423860_bApe5ResfiVkO0G0UlUjUVNpAtFUWYYy.jpg"
},
{
"name": "Nest Tame",
"profPic": "https://thumbs.dreamstime.com/z/happy-university-college-student-thumbs-up-15010463.jpg"
}
]
Here is my database .js for the cards
import mongoose from 'mongoose';
const cardSchema = mongoose.Schema({
name: String,
profPic: String
});
export default mongoose.model('cards', cardSchema);
Assuming your DB Connection is ok?? I think your issue lies in the structure of your code. According to the mongoose documentation, your first parameter should be an empty object followed by the callback to return all records like the example given below.
Cards.find((err, data) => {
if (err)
{
res.status(500).send(err);
}
else
{
res.status(200).send(data);
}
});
Example
Cards.find({}, (err, docs) => {
if (err) {
res.status(500).send(err);
}
res.status(200).send(docs);
});

update a document using mongodb by the Id of the document

how to update a document using mongodb by the Id of the document, this is what I tried to do:
I am retrieving the document with the given id from the db,
then construct a new user with the information provided by the user
and update the userinformation to the db.
var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, async function (err, db) {
console.log(args);
if (err) throw err;
var dbo = db.db("UserApp");
//retrieve the document with the given id from the db
let user = await dbo
.collection("users")
.findOne({ _id: ObjectId(args.id) }, function (err, result) {
if (err) throw err;
console.log(result);
});
const myquery = { name: user.name };
// construct a new user with the information provided by the user
const newuser = new User({
name: args.name,
title: args.title,
email: args.email,
});
// update the userinformation to the db
dbo.collection("users").updateOne(myquery, newuser, function (err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});
});

MongoJS Insert Method Not Creating Collection in MongoDB & Robo 3T

I am using MongoJS and would like to auto-create a new collection called "Comments" in my MongoDB via the code below...Not working and can't seem to figure out why. Thanks for any insight you can provide!
app.post("/post", function(req, res) {
db.comments.insert({
articleId: JSON.stringify(req.body._Id),
name: JSON.stringify(req.body.chatId),
message: JSON.stringify(req.body.message)
}),function(err, response) {
if(err) {
console.log(err);
} else {
console.log("This is working!");
}
}});
If you use the body-parse middleware:
app.post("/post", function(req, res) {
let { body } = req;
db.comments.insert({
articleId: body._Id,
name: body.chatId,
message: body.message
}),function(err, response) {
if(err) {
console.log(err);
} else {
console.log("This is working!");
}
}});
and if not , just use it like:
let parsed;
try {
parsed = JSON.parse(res.text)
} catch(err){req.send(err)}
// now you have:
parsed._Id ...

MongoDB query won't return object in my Express API (React)

I have done this so many times before, but I can't seem to find the issue, it's probably something small and stupid. Take a look at the /server.js file here! (Shortened for demonstration purposes)
/* Make Mongoose promise based */
mongoose.Promise = Promise;
mongoose.connect('mongodb://localhost:27017', options);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
/* Routes */
app.route('/games')
.post(postGame)
.get(getGames);
app.route('/games/:id')
.get(getGame)
.delete(deleteGame);
app.route("*").get((req, res) => {
res.sendFile('client/dist/index.html', { root: __dirname });
});
const port = 8080;
app.listen(port, () => {
console.log(`Connected! Server listening on port: ${port}`);
});
Then for my Game model, I have that in app/models/game.js.
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const gameSchema = new Schema(
{
name: {
type: String,
required:true
},
year: {
type: Number,
required:true
},
description: {
type: String,
required:true
},
picture: {
type: String,
required:true
},
postDate : { type: Date, default: Date.now }
}
);
export default mongoose.model('Game', gameSchema);
This is where I believe I am having the issue.
/* Import Game model schema */
import Game from '../models/game';
const getGames = (req, res) => {
Game.find({}, (err, games) => {
console.log(err, games)
if (err) {
res.send(err);
}
res.json(games);
});
}
const getGame = (req, res) => {
const { id } = req.params;
Game.findById(id, (err, game) => {
if (err) {
res.send(err);
}
res.json(game);
});
}
const postGame = (req, res) => {
let game = Object.assign(new Game(), req.body);
game.save(err => {
if (err) {
res.send(err);
}
res.json({ message: 'Game successfully created!' });
});
};
const deleteGame = (req, res) => {
Game.remove(
{ _id: req.params.id },
err => {
if (err) {
res.send(err);
}
res.json({ message: 'Game successfully deleted!' });
}
);
};
export {
getGames,
getGame,
postGame,
deleteGame
};
Just do be clear... I went into the mongo shell.
I did...
connecting to: test
> db.createCollection('Game')
> db.Game.insert({name: "SSB", year: 2001, description: "Fun Game", picture: "http://google.com", postDate: "2017-01-03T08:51:45.888Z"});
And when I type > db.Game.find({}); I am returned with exactly what I have...
{
"_id" : ObjectId("58c2223e32daa04353e35bdc"),
"name" : "SSB",
"year" : 2001,
"description" : "Fun Game",
"picture" : "http://google.com",
"postDate" : "2017-01-03T08:51:45.888Z"
}
You see when I go to http://localhost:8080/games I am returned with an empty JSON and I just wanna know why. I am 70% sure, it is because it isn't connected to the right collection but I don't remember how to test that :(
I wanted to make this a comment but it won't let me because I don't have a 50 reputation, but I believe I found the issue.
const getGame = (req, res) => {
const { id } = req.params;
Game.findById(id, (err, game) => {
if (err) {
res.send(err);
}
res.json(game);
});
}
In this piece of code you are setting the id to req.params, but you need to set it to req.params.id which is what you passed in your route.
Should look like this:
const {id} = req.params.id;
If you logged id, you would probably get an object that says:
{ id: "[whatever_id_you_put_here]" }
however if you log req.params.id you should get the correct id you put in that spot..
The reason you're getting [] is because you're actually connected to the database and you are actually trying to "get" something, but that something doesn't exist so it sends an empty response.
I hope this helps..

Query mongoDB with mongoose model

Im using the find() method to get all data from a mongoDB like this
exports.getPersona = function (req, res){
Persona.find( function(err, persona) {
if (err)
res.send(err)
res.json(persona); // return all personas in json
}
);
}
Im trying to do a query like this:
exports.getPersona = function (req, res){
Persona.find(
{
faceDetection: {
name: "Borja"
}, function(err, persona) {
if (err)
res.send(err)
res.json(persona);
}
);
}
But i dont find nothing. My mongoose model is:
var faceDetectionSchema = mongoose.Schema({
faceDetection: {
name: String,
surname: String,
}
});
What could be the problem? Thanks a lot.
Edit: the document its a JSON like:
{
"faceDetection": {
"name": "Borja",
"surname": "Good"
}
Looks like your parentheses and braces are out of order. Try this below.
exports.getPersona = function(req, res) {
Persona.find({
'faceDetection.name': "Borja"
}, function(err, persona) {
if (err)
res.send(err)
res.json(persona);
})
}