0

Background I just started learning how to use node.js and mongodb. iv been able to create a db and connect to it / write a collection using the code below

var url = "localhost:27017/TheDatabase";
var collections = ["Location"];
var mongojs = require("mongojs")
var db = mongojs(url, collections);

var object = {
    "place" : {
        "address" : "123 road",
        "code" : "ABC CDE",
        "letters" : "AA",
        "coord" : [  99.55, -20.5 ]
    },
    "keyword1" : "World",
    "keyword2" : "Biomech",
    "keyword3" : "Spotify",
    "_id" : "1"
}

db.Location.save(object);

The Problem I was unable to successfully retrieve the data from this database/collection. What i want to do is just retrieve "object" from db and display it to terminal to see i accomplished the store/retrieve correctly.

What i'v tried I'v opened mongo.exe and tried running

use TheDatabase
show collections
db.Location.find()

and was able to see the data. I'm not sure how i implement this in my node.js application.

Edit

    db.Location.find(function (err, docs) {
    console.log(docs);// docs is an array of all the documents in mycollection
})
Community
  • 1
  • 1
Singh
  • 301
  • 2
  • 6
  • 16
  • Have you tried just issuing a `.find()`? Also note that calls like `.save()` are asynchronous and therefore should have a callback to indicate completion and the following code to run. You appear to be using [mongojs](https://github.com/mafintosh/mongojs), so you might at least try looking at the documentation. Or at least show the code you have tried here in the "application" rather than the shell. – Blakes Seven Feb 18 '16 at 00:48
  • Read the comment a bit more closely. "Inside the callback". See: [How to return the Result from an asynchronous call](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Blakes Seven Feb 18 '16 at 01:02
  • Thanks a lot! I got it. Sorry for asking such basic questions. – Singh Feb 18 '16 at 01:10
  • @BlakesSeven if i wanted to drop the database so this application could be run multiple times with a clean database, where would i add the db.dropDatabase() line? – Singh Feb 18 '16 at 01:32
  • Look at the documentation. If you see it there it's a method, but likely it's a [database command](https://docs.mongodb.org/manual/reference/command/) instead that you need to issue. If you have other questions, then [Ask Another Question](http://stackoverflow.com/questions/ask). But please at least search and research documentation before you do that. – Blakes Seven Feb 18 '16 at 01:35

0 Answers0