Bad Request from mongolab - mlab

Below is my controller:
'use strict';
app.controller('editTaskCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
var taskid = $routeParams.id;
$http.get('https://api.mongolab.com/api/1/databases/dothis/collections/newtask?q={"_id":'+taskid+'}&apiKey=_______-yyNsxk___-____21jxrS___').success(function (data, status, headers, config) {
$scope.lists = data;
console.log(data);
}).error(function (data, status, headers, config) { alert(status); });
}]);
When i send a request to mongolab it gives me "Bad Request".
here is my requst URL:
GET https://api.mongolab.com/api/1/databases/dothis/collections/newtask?q={%22_id%22:56b06ff8e4b0f641cb6d3a76}&apiKey=_______-yyNsxk___-____21jxrS___ 400 (Bad Request)
Here I want a mongodb collection document using mongolab api and collection id i.e. (_id);
please tell me where is the error?

Querying on the _id field via the MongoLab Data API takes a different format than other queries.
GET /databases/{database}/collections/{collection}/{_id}
Example:
https://api.mongolab.com/api/1/databases/my-db/collections/my-coll/4e7315a65e4ce91f885b7dde?apiKey=myAPIKey
Please refer to our documentation for further information: http://docs.mongolab.com/data-api/.

Related

Express - return certain documents with named route parameters using axios

I'm having trouble communicating between the frontend and backend for a selected GET request.
I am using a React frontend with an express/mongoose setup out in the backend.
In the frontend, I do a GET call using axios for:
axios.get('/api/orders/', {
params : {
name: this.props.user.name // user name can be Bob
}
})
And in the backend I'm having a hard time understanding the correct method I would need to do to query the database (example below doesn't work). I found stuff with .select but even then I still can't get it to work:
router.get('/orders', function(req, res) {
Order.find({}).select(req.params).then(function (order) {
res.send(req.params);
})
});
I also tried doing this to see if I can even get the params to send properly and to no demise:
router.get('/orders/:name', function(req, res) {
res.send('client sent :',req.query.name);
});
The orders document model holds objects that house an ordered array and a name (type: String) attached to the object. The Mongoose scheme for the order:
const orderScheme = new Schema({
name : { type : String },
orders : { type : Array}
});
In my MongoDB, I can see all the "Master Orders" send back. Each master order has the name of who submitted it, plus all the orders within (there can be a ton of orders).
What I'm trying to exactly do is pull up all orders that have a certain name. So if I search "TestAccount", I'll get all of bob's orders. I've included an image below:
Any pointers?
Client-side:
axios.get('/api/orders/' + this.props.user.name)
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
You need to handle the Promise when resolved/rejected.
Server-side:
router.get('/orders/:name', function(req, res) {
return Order.find({name: req.params.name}).then(function(orders) {
// return orders when resolved
res.send(orders);
})
.catch(function (error) {
// handle error
console.log(error);
})
});
You did not specify a named route parameter in your route path.
You also aren't accessing the name property by using req.params only.
You should use Model.find() conditions parameter to specify which document[s] you're trying to find. Query.prototype.select() is for filtering document fields.

TypeError: Cannot read property '_id' of undefined at insertDocuments at insertOne

I was trying to insert a record into a collection when this error was thrown. I went through the mongodb doc on insertOne and I understand that mongod will automatically add the _id when it is not specified as in my case, so I'm wondering why there is an undefined id error.
Here's the code I'm working with, first the api route and the data I'm trying to insert
app.post('/api/contacts', (req, res) => {
// retrieve the user being added in the body of the request
const user = req.body;
// obtain a reference to the contacts collection
const contactsCollection = database.collection('contacts');
// insert data into the collection
contactsCollection.insertOne(user, (err, r) => {
if (err) {
return res.status(500).json({error: 'Error inserting new record.'});
}
const newRecord = r.ops[0];
return res.status(201).json(newRecord);
});
});
The json data for inserting
{
"name": "Wes Harris",
"address": "289 Porter Crossing, Silver Spring, MD 20918",
"phone": "(862) 149-8084",
"photoUrl": "/profiles/wes-harris.jpg"
}
Database connection to the to the database hosted on mlab is successful with no errors. What could possibly be wrong here and how do I go about fixing this error?
The error message means that the object that you are passing into insertOne is undefined (and hence it can’t read the _id property of of it). You might like to look at what exactly req.body contains as that is what is passed as user. (I don’t know TypeScript but, in node/express, I have had errors like this when I didn’t set up bodyParser correctly)
Faced a similar problem. Solved and it by using body-parser and then parsing the json object being sent as follows:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// parse application/json
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})

TypeORM FindById doesn't work with MongoDB

I'm trying to use TypeORM with MongoDB and express but I'm having problems with the basic stuff.
I just created a controller with basic CRUD operations for an entity. The methods save, findAll and find by Filter works ok, but I can't make the methods that require an mongo id work.
router.get("/", async(req: Request, res: Response) => {
const investmentRepository = getMongoRepository(Investment);
const investments = await investmentRepository.find();
res.send(investments);
});
router.get("/:id", async(req: Request, res: Response) => {
const investmentRepository = getMongoRepository(Investment);
const investment = await
investmentRepository.findOneById(req.params.id);
if (!investment) {
res.status(404);
res.end();
}
res.send(investment);
});
The second method is always returning 404.
For example, this is an entity returned on get all "investment/"
{
"id": "59dfd8cadcbd9d1720457008",
"name": "Teste LCI",
"startDate": 1466305200,
"numberOfDays": 365,
"type": "LCI_LCA"
}
If I try to send a request for this specific object calling
investment/59dfd8cadcbd9d1720457008
the response is always 404.
The same behavior happen with the delete method, raising an exception
Cannot find entity to remove by a given id
I also tried to convert the string to ObjectID using:
new ObjectID(req.params.id);
but it fails with the error ObjectID is not a constructor.
If you're receiving the error ObjectId is not a constructor it is because you forgot to require it in your file. All you need is:
const ObjectId = require('mongodb').ObjectId;

Error updating mongoDB document using Postman

I am trying to update a record from mongoDB collection using Postman.
This is the code I am using to do it.
// Update message with id (using a PUT at http://localhost:8080/messages/:message_id)
router.route('/messages/:message_id')
.put(function(req, res) {
Message.findById(req.params.message_id, function(err, message) {
if (err)
res.send(err);
// Update the message text
message.text = req.body.text;
message.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Message successfully updated!' });
});
});
});
//Updating A Message end.
Next, this is the URI I am typing in Postman to update (based on the id key):
localhost:8080/messages/ObjectId("58ab37f9d23f991791490963")
Then I get this error message:
I am trying to commit to a Bitbucket repository.
What should I change in the URI to make the update valid?
You may want to drop the ObjectId part from what you are posting and just send the id itself then create an ObjectId on the server
localhost:8080/messages/58ab37f9d23f991791490963
router.route('/messages/:message_id')
.put(function(req, res) {
var id = new ObjectId(req.params.message_id)
Message.findById(id, function(err, message) {
...
})

Get all matching items using ids array form database

I can't receive list of items that matches with my array of ids.
This is PART of code in Angular component:
this.orderService.getSpecyficOrders(ids)
.subscribe(orders => { ...
Where ids is an array of
[{_id : ID },{_id : ID },{_id : ID },]
ID is "5235sd23424asd234223sf44" kind of string form MongoDB documents.
In angular service file I have imported:
Http, Headers, and import 'rxjs/add/operator/map';
Here is code in service in Angular:
getSpecyficOrders(ids){
return this.http.get('/api/ordersspecyfic', ids)
.map(res => res.json());
}
In express file I have require: multer, express,router,mongojs, db
And here is part of code in express, call to mongodb:
router.get('/ordersspecyfic', function(req, res, next){
var ids = req.body;
ids = ids.map(function (obj){ return mongojs.ObjectId(obj._id)});
db.orders.find({_id: {$in: ids}}, function(err, orders){
if(err){
res.send(err);
}
res.json(orders);
});
});
And I'm getting error:
Uncaught Response {_body: "TypeError: ids.map is not a function
&n…/node_modules/express/lib/router/index.js:46:12)↵", status:
500, ok: false, statusText: "Internal Server Error", headers:
Headers…}
Console.log in express file
is showing me that req.body is an empty object {}
As far as I know req.body is not an array, but I don't know if this is only problem with that code.
All others request of get single element, get all items etc. are working fine.
I just can't get this one working..
I assume you are trying to send ids to your server side with
return this.http.get('/api/ordersspecyfic', ids)
but http.get api doesn't work like that
get(url: string, options?: RequestOptionsArgs) : Observable
In order to send this data to your back-end you should use the post api
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('/api/ordersspecyfic', ids, options)
post(url: string, body: any, options?: RequestOptionsArgs) : Observable
Source:https://angular.io/docs/ts/latest/api/http/index/Http-class.html
Two errors, backend and frontend.
Frontend error
You say this.http.get('/api/ordersspecific', ids);. This does nothing - or specifically, this only tries to get /api/ordersspecific. It doesn't send ids, your second parameter doesn't match any RequestOptions. In other words, your ids are ignored.
You'd want to append this as a query string. Check here how to add querystring parameters. But in short, it'd be something simple like:
return this.http.get('/api/ordersspecyfic?ids=<id1>&ids=<id2>...'
Backend error
You're reading stuff from body. It's a GET request, there should be no body. Read this from querystring:
router.get('/ordersspecyfic', function(req, res, next){
var ids = req.query.ids;
});