Get value from MongoDB - javascript

I am new in MongoDB. I have a MongoDB collection with structure like in the image below.
I want to console log the value of item. So, I want to console log "journal". How can I do that? I would appreciate any help.

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost/EmployeeDB';
var ObjectId = require('mongodb').ObjectId;
MongoClient.connect(url, function(err, db) {
db.collection('collection_name').findOne({
_id:ObjectId("61412a7bf30b9 .... ") /// doc _id
}).then(r=>{
console.log(r.item)
});
});

Related

Cannot read property 'insert' of undefined when trying to put data in MongoDB

I'm getting this error: "Cannot read property 'insert' of undefined" when trying to insert data into a database. The error shows on:
db.coordinates.insert({ "x" : "data.x", "y" : "data.y"})
Database name - "node5"
Collection name - "coordinates"
// Including libraries
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var static = require('node-static'); // for serving files
//db connection
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/node5');
var url = 'mongodb://localhost:27017/node5';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server.");
db.close();
});
// This will make all the files in the current folder
// accessible from the web
var fileServer = new static.Server('./');
// This is the port for our web server.
// you will need to go to http://localhost:8080 to see it
app.listen(8080);
// If the URL of the socket server is opened in a browser
function handler(request, response) {
request.addListener('end', function () {
fileServer.serve(request, response);
}).resume();
}
// Delete this row if you want to see debug messages
io.set('log level', 1);
// Listen for incoming connections from clients
io.sockets.on('connection', function (socket) {
// Listen for mouse move events
socket.on('post', function (data) {
console.log('posted');
console.log(data);
socket.broadcast.emit('posted', data); // Broadcasts event to everyone except originating client
db.coordinates.insert({ "x" : "data.x", "y" : "data.y"})
});
});
When writing an answer, please note that I'm new to node.js and I might not understand if you tell the answer in a complex way:)
If you are using monk for your project, then you can drop the mongodb module, since it's functionality is being wrapped up by monk. From Monk's documentation, you should be doing something like:
const monk = require('monk');
const db = monk('localhost:27017/node5')
const coordinates = db.get('coordinates');
Now that you have a reference to your coordinates collection, you can use it later in your code:
coordinates.insert({ x: data.x, y: data.y });
I hope this is easy enough to understand. If it is still confusing, then please comment below and I'll elaborate further :)

Inserting Into A Mongodb Collection (Newbie)

I'm new to nodejs and mongodb. I'm trying to insert newClass into the class collection. Everything seems to be working except this function. It gives a 500 error and doesn't save the class.
I checked the mongodb docs and it seemed correct. Can someone please point me in the right direction?
routes
Class.createNewClass(newClass, function(err){
if (err){
console.log(err);
res.send(err);
} else {
console.log('Class saved.")
}
})
model
module.exports.createNewClass = function(newClass, callback){
Class.insert({newClass}, callback);
}
There's a syntax error in your createNewClass function, assuming the newClass variable is an object that contains all the key:value pairs you're saving to the new document, you should remove the curly braces:
module.exports.createNewClass = function(newClass, callback){
Class.insert(newClass, callback);
}
That said, the code you posted for your routes doesn't look much like a route to me, so there could be other errors your transcription is not revealing.
I'm not really clear on the overall structure of your app, but here is a very simple Express app that can insert new classes to the database.
var express = require('express');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var app = express();
app.use(bodyParser.json());
var MongoClient = require('mongodb').MongoClient;
var db;
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/school", function(err, database) {
if(err) throw err;
db = database;
// Start the application after the database connection is ready
app.listen(3000);
console.log("Listening on port 3000");
});
app.post('/class', function(req,res) {
var collection = db.collection('classes');
var newClass = req.body;
console.log(req.body);
collection.insert(newClass);
res.json(newClass);
});
In your model change it to:
module.exports.createNewClass = function(newClass, callback){
Class.collection.insert(newClass, callback);
};
Check that "Class" should be schema model object.
module.exports.createNewClass = function(newClass, callback){
new Class(newClass).save(callback);
};
It's the basic mongoose way. In mongoose we use "insert" to multiple documents but you can also use insert for single document.

Using mongo-triggers

I have just installed mongo-triggers via:
npm install mongo-triggers
I am trying to have a hello world running:
var MongoClient = require('mongodb').MongoClient;
var triggers = require("mongo-triggers");
MongoClient.connect('mongodb://localhost:27017/mydatabase', function(err, db) {
triggers(db.mycollection).insert(function(document, next) {
console.log("Triggered on insert");
next();
});
});
I get a:
TypeError: Cannot read property 'save' of undefined
I am just not very familiar with js so I may have miss sth. Can someone help?
instead of
var MongoClient = require('mongodb').MongoClient; require("mongo-triggers");
Try
var MongoClient = require('mongodb').MongoClient;
var triggers = require("mongo-triggers");
I just solved the problem, here is the full working code:
var MongoClient = require('mongodb').MongoClient;
var triggers = require("mongo-triggers");
MongoClient.connect('mongodb://localhost:27017/mydatabase', function(err, db) {
var myCollection = db.collection('mycollection');
triggers(myCollection).insert(function(document, next) {
console.log("Triggered on insert");
next();
});
});
But it has led me to another problem, when I insert sth in the db, on CLI for example with:
> use mydatabase
> db.mycollection.insert({"mytest": 1})
Nothing is triggered (no print on stdout). I think I am gonna make another post for this one ^^

nodejs sends empty response before data retrieved from mongodb

When I use jQuery ajax to retrieve data from nodejs (with express4), nodejs sends empty response back before data loaded from mongodb.
This is the message from nodejs console:
GET /query?uid=1 - - ms - -
And this is the error message from Chrome console:
GET http://192.168.1.105:3000/query?uid=1 net::ERR_EMPTY_RESPONSE
I can confirm that data are correctly loaded from mongodb because data can be printed on nodejs console after nodejs sent the empty response. And this is exactly the problem. Why nodejs sends reponse to client before data have been prepared?
I know nodejs is asynchronous and I pay much attention to this great feature, but I still have this problem.
This is my client code:
$.getJSON('/query', {uid:1}, function(response) { console.log('finished!'); });
And this is my server code:
var express = require('express');
var mongodb = require('mongodb');
var GeoJSON = require('geojson');
var strftime = require('strftime');
var router = express.Router();
var MongoClient = mongodb.MongoClient;
router.get('/query', function(req, res, next) {
var url = "mongodb://localhost/example_db";
var collection_name = "example_collection";
var poi = req.query.poi ? req.query.poi.split("||") : null;
var time = req.query.time;
var uid = req.query.uid;
var condition = {};
if (poi) condition.poiname = {$in: poi};
if (time) condition.checkin_time = {$gte:new Date(time.start_time), $lte:new Date(time.end_time)};
if (uid) condition.uid = parseInt(uid);
MongoClient.connect(url, function(err, db) {
if (err) console.log('connection error');
var collection = db.collection(collection_name);
collection.find(condition).sort({checkin_time:1}).toArray(function(err, result) {
if (err) {
console.log(err);
return res.send('error!');
}
if (!result) return res.send('no data');
//This line prints the result after empty response has been sent.
console.log(result);
var data = {};
data['geojson'] = GeoJSON.parse(result, {Point:'loc', include:['poiname', 'uid', 'checkin_time']});
res.json(data);
db.close();
});
});
My data are a little bit large, 12G stored in mongodb. So it usually takes about 3 minutes or more to complete the query. When I use findOne to retrieve only a single document, this is no problem.
Does the data size cause the problem?
Try GeoJSON.parse with callback
var data = {};
GeoJSON.parse(result, {Point:'loc', include:['poiname', 'uid', 'checkin_time']}, function (geojson) {
data['geojson'] = geojson;
res.json(data);
db.close();
});

Failing while comparing params on express (get request)

I'm using express 3.0 and when I'm trying to resolve some queries I want to test if there's other component on the db that match these id's. Any way, this is the code I'm not getting to work:
function(req, res) {
var Parking = mongoose.model('Parking');
var parkingId = req.params.id;
var userId = req.user['_id'];
Parking
.findOne({'_id': parkingId}, function(err, parking) {
var parkingUserId = parking.userId;
if (userId == parkingUserId) {
...
} else {
...
}
req.params.id is inside url and req.user['_id'] comes from a middleware.
Although I'm calling this url with the same id on both fields.... it keeps getting false...
Why I'm doing wrong? thanks!
You need to convert parkingUserId from a bson ObjectId object to a string:
if (userId.toString() == parkingUserId.toString())

Categories

Resources