How to query mongoDB using mongoose? - json

How do you query MongoDB using mongoose with node.js? I have it to where I can insert my JSON object to my DB, but all the ways I have tried to return the JSON object from the DB return null or just information about the database.
Is there some good method using mongoose to be able to query the database similar to the method:
var cursor = db.collection.find()
var JSONobject = cursor.next()
Here's what is in my code right now:
mongoose.connect('mongodb://localhost/myDB');
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
var cursor = mongoose.connection.db.contents.find();
console.log(cursor.next());
This throws an error at the line :
var cursor = mongoose....
claiming 'cannot call method 'find' of undefined'.
Note, that my collection 'contents' does in fact exist, and it contains one JSON document. I know this because I manually navigated to the collection using the mongo shell.
Edit: I am open to alternative methods to querying the database. I simply just want to be able to return JSON objects from my DB one at a time, while keeping track of where the client is at in the database.

One method to query mongoDB using mongoose is as follows:
Content.findOne().exec(function(err,docs){console.log(docs)});
Docs contains the JSON object. Access its attributes like any other object.
Note, this method uses asynchronous call backs. As such, you can't store the JSON object docs to a variable in order to use the JSON document information outside of the function. Therefore, you need to perform whatever actions needed with the JSON docs object information inside of the function.
For example, I was needing the query information to provide the filepath for my get api. As such, the result was as follows:
//get
app.get('/api/media/', function(req,res){
Content.findOne().exec(function(err,docs){res.sendFile(path.join(__dirname, '/api/media/', docs.filename))});
});
Note, Content is the model of my schema, and one of its parameters is filename.

Related

Merging two JSON Objects in Node-Red

I am having some trouble trying to merge two JSON objects retrieved from my SQL Server database into a single object in Node-Red.
The flow I have created is the following:
For each call to the database I am receiving the following objects:
Plans:
[{"PlanID":2,"Status":0,"EndTime":"0001-01-01T00:00:00.000Z"}]
Goals:
[{"GoalID":1,"PlanID":2, "Type":2,"Message":"Walk 1000 km","Difficulty":0}]
I have created two functions which assign these objects into flow variables ('plans' and 'goals'), and now I was trying to merge both objects into a single JSON object.
I don't know if I have to use the Join node for this purpose and if so how to configure it, but my idea was to create a JSON object in this format:
[{"GoalID":1,"Plan":{"PlanID":2,"Status":0,"EndTime":"0001-01-01T00:00:00.000Z"}, "Type":2,"Message":"Walk 1000 km","Difficulty":0}]
First I wouldn't set them as flow variables as these will get over written if you get a second request in to the http-in node while the Database look ups are happening. Better to add them as msg variables then they flow with the msg and can't be overwritten.
Given you are not just combining the 2 objects to get the super set of keys and values you are probably best off just using either a function node or the change to assemble to the output object yourself.
Assuming the input looks something like:
msg.plans = [{"PlanID":2,"Status":0,"EndTime":"0001-01-01T00:00:00.000Z"}]
msg.goals = [{"GoalID":1,"PlanID":2, "Type":2,"Message":"Walk 1000 km","Difficulty":0}]
then the function node would look something like:
msg.payload = msg.goals[0];
msg.payload.plan = msg.plans[0];
delete msg.goals;
delete msg.plans;
return msg;
The change node rules would looks something like
The join node would work to get the 2 objects into an array or an object using the topics as keys to hold the 2 input messages.

MongoDB Updating collection document with json object imported by client in meteor

I have a JSON object that is imported by the client (imported as XLSX and converted to JSON).
Every JSON object has a reference and other several fields that get inserted in my collection.
What I'm trying to do is whenever a client imports a JSON object with a reference that is already in one of my collection documents I want to update that document with the updated fields and new ones imported by the client.
This is how I'm trying to reach it:
let keys = Object.keys(json.data[0]);
let values = Object.values(json.data[0]);
Adverts.update({'reference': json.data[0].reference}, {$set: {keys: values}}, {upsert: true});
I've checked the docs and other answers, seems like with upsert and $set is the way to go, but I don't know what I'm doing wrong.
Thanks.
keys and values are arrays, you can't do this:
... {$set: {keys: values}} ...
Instead try this:
Adverts.update({'reference': json.data[0].reference},
{$set: json.data[0] }, {upsert: true});

Adding query Parameters to Go Json Rest

I am using the library go-json-rest. I'm trying to recognize queries parameters in the code for example localhost:8080/reminders?hello=world I want to access {hello: world} . I have the following code:
//in another function
&rest.Route{"GET", "/reminders", i.GetAllReminders},
func (i *Impl) GetAllReminders(w rest.ResponseWriter, r *rest.Request) {
reminders := []Reminder{}
i.DB.Find(&reminders)
w.WriteJson(&reminders)
}
I know that r.PathParams holds the url parameters but I cannot seem to find how to the query parameters past the "?" in the url.
Given that go-json-rest is a thin wrapper on top of net/http, have you looked at that package's documentation? Specifically, the Request object has a field Form that contains a parsed map of query string values as well as POST data, that you can access as a url.Values (map[string][]string), or retrieve one in particular from FormValue.

How to access all the entries in MySQL table in Django View?

I am designing a Web Application using Django Framework. I have written the model code, urls.py and view code which can be seen Here.
I have added some data into the database table. But when I try to access the object using the code below, it just shows bookInfo objects five times. I don't think I am successful enough in pulling the data from the database. Kindly help.
View
def showbooks(request):
booklist = bookInfo.objects.order_by('Name')[:10]
output = ','.join([str(id) for id in booklist])
return HttpResponse(output)
You are iterating through the object list, you just need to reference the column/attribute you want:
output = ','.join([obj.id for obj in booklist])
Alternatively you can more more finely craft you original db call, then the iterable you use will work. In this case we'll pull out a list of the 'id' attribute.
booklist = bookInfo.objects.order_by('Name').values_list('id', flat=True)[:10]
output = ','.join([id for id in booklist])
I think you are successful in pulling the data. It is just that booklist contains objects, not numeric ids. You can add __unicode__ method to you class BookInfo that is supposed to return a string representation of the object (probably book name in this case). This method is going to be invoked when str() is applied. You can find more info about __unicode__ here.

CakePHP Accessing Dynamically Created Tables?

As part of a web application users can upload files of data, which generates a new table in a dedicated MySQL database to store the data in. They can then manipulate this data in various ways.
The next version of this app is being written in CakePHP, and at the moment I can't figure out how to dynamically assign these tables at runtime.
I have the different database config's set up and can create the tables on data upload just fine, but once this is completed I cannot access the new table from the controller as part of the record CRUD actions for the data manipulate.
I hoped that it would be along the lines of
function controllerAction(){
$this->uses[] = 'newTable';
$data = $this->newTable->find('all');
//use data
}
But it returns the error
Undefined property:
ReportsController::$newTable
Fatal error: Call to a member function
find() on a non-object in
/app/controllers/reports_controller.php
on line 60
Can anyone help.
You need to call $this->loadModel('newTable') to initialize it properly. Cake needs to initialize $this->newTable properly, and call all the callbacks.
Of course, you don't need $this->uses[] = 'newTable';, that doesn't do anything except add another value to the $uses array.
try:
function controllerAction() {
$data = ClassRegistry::init('ModelNameForNewTable')->find('all');
}
If your table is called 'new_tables', your model name should be 'NewTable'