Inserting Into A Mongodb Collection (Newbie) - javascript

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.

Related

Get value from MongoDB

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)
});
});

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 :)

Node.js: Using Socket.io in an express.js route to send message to a specific client

I have made a very casual commenting system, and now I want to add replies. So, when someone posts a reply on someone else's comment, that user must be notified that someone replied to their comment. In order to do that, when the replier clicks the reply button an AJAX post request is made to the server, the server then needs to get the id of the first commenter and send them a response text using socket.io (socket.io is not required to be used if there is another way to send the reply text with another module or express itself). This is my code so far:
app.post('/reply', function(req, res){
var commenterId = req.body.userId; // this is the id of the original commenter, not the replier
User.findOne({'_id':commenterId}, function(err, user){
user.send({'replied': req.user._id}); // this is what I need to do, and
//I don't know if this specific code works and that's why I'm asking if there is a way to do it with socket.io,
// io.to(socketId).emit('reply', 'some reply text here...'); // but if I do this I don't know how to get the socketId!
//Is there even a way to do this? Maybe with another module,
//or some express function I don't know about? And if it is done with express how would
//the client side code, look like? Thank you!
});
res.end();
});
//app.js file
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var routes = require('./routes/routes')(io);
app.use('/', routes);
//router file
var express = require('express');
var router = express.Router();
var _socket = null;
//list of socket users.once they logout delete the socket by
//delete users[_socket.userid];
var users = {};
var returnRouter = function(io) {
io.sockets.on('connection', function (socket) {
//now _Socket is available inside routes
_socket = socket;
});
router.post('/login', function(req, res) {
//authentication logic
User.findOne({'email': req.body.email}, function (err, user) {
//userid must be unique
_socket.userId= user.userId
//set session variable to store id of the user
req.session.userId = user.userId;
//now every user has a socket associated with their id
users[_socket.userId] = _socket;
});
});
router.post('/reply', function (req, res) {
var commenterId = req.body.userId;
User.findOne({'_id': commenterId}, function (err, user) {
// you can get the id of the logged in user that is the creator
//of the original post from req.session.userId
//if you have implemented session store
//the commenter user object is obtained from findOne method
users[req.session.userId].emit('notification', {
notification: user.username+' commented on your post'
}});
});
res.end();
});
return router;
};
module.exports = returnRouter;

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 ^^

How to use a MongoDB collection in another file

I have one server file that is server.js.
I have a MongoDB connection inside this file like this:
var Db=require('mongodb').Db;
var BSON=require('mongodb').BSONPure;
var Server=require('mongodb').Server;
client=new Db('database' , new Server('127.0.0.1',27017),{safe:false});
client.open(function(err,pClient)
{
client.collection('userdetails',function(err,collection)
{
Ucollection=collection;
});
});
I have another file named server2.js. In this file I have to check if a username exists or not from Ucollection (this is collection name).
How can I give the MongoDB connection to server2.js? How can I use this collection in server2.js?
You could do something like this
in server.js:
var Db=require('mongodb').Db;
var BSON=require('mongodb').BSONPure;
var Server=require('mongodb').Server;
global.mongoHelper = {};
global.mongoHelper.db = Db;
global.mongoHelper.bson = BSON;
global.mongoHelper.server = Server;
client=new Db('database' , new Server('127.0.0.1',27017),{safe:false});
client.open(function(err,pClient)
{
client.collection('userdetails',function(err,collection)
{
Ucollection=collection;
});
});
in server2.js
client=new global.mongoHelper.db('database' , new global.mongoHelper.server('127.0.0.1',27017),{safe:false});
client.open(function(err,pClient)
{
client.collection('userdetails',function(err,collection)
{
Ucollection=collection;
});
});
I think much cleaner way of doing this is to seprate your database configration into seprate file. Like this
in database-config.js
var Db=require('mongodb').Db;
var BSON=require('mongodb').BSONPure;
var Server=require('mongodb').Server;
client=new Db('database' , new Server('127.0.0.1',27017),{safe:false});
module.exports.connectDatabase = function(callback){
client.open(function(err,pClient)
{
if(err){
console.log(err);
process.exit(1);
}
module.exports.userCollection = pClient.collection('userdetails');
callback();
});
}
in server.js
var database = require('./database-config')
database.connectDatabase(function() {
//here you can reuse collection like this
database.userCollection
}
in server2.js
var database = require('./database-config')
//here you can reuse collection like this
database.userCollection
I am assuming that server.js is your main file which actually intiate server so when you run your application it connects to database and load required collections which you can use anywhere in your application like I did this is considered as best practice to re-use collections. Let me know if there is any confusion
Well you are a bit mistaken about the whole concept of modularizing the code. For your task, you should not make a second server.js. You can make another module say, verifyUser and require it in your server.js file. You may require it (may be) after your mongodb connection.
server.js
var Db=require('mongodb').Db;
var BSON=require('mongodb').BSONPure;
var Server=require('mongodb').Server;
client=new Db('database' , new Server('127.0.0.1',27017),{safe:false});
client.open(function(err,pClient)
{
exports.Ucollection=pClient;
});
});
server2.js
var mongodb = require('mongodb');
var mainApp=require('./server');
var collectionObj=mainApp.Ucollection;
var collection = new mongodb.Collection(collectionObj, 'userdetails');
Using this collection.you can query like below
collection.insert(userInfo,{safe:true},function(err, objects) {
if(!err){
console.log('Data inserted successfully.');
}
});

Categories

Resources