Using mongo-triggers - javascript

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

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

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.

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;

Node.JS undefined is not a function on required module

I'm trying to use a class that I created called user.js. The code for this user is:
function User(){};
User.prototype.addUser = function(){
//Do stuff
return 0;
};
module.exports = User;
I'm including it in my index.js route file, which looks like this:
var config = require('../lib/config');
var db = require('../lib/db');
var User = require('../lib/user');
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* GET create user. */
router.get('/newuser', function(req, res, next) {
*****var newuser = User.addUser();*****
res.render('index', {
user: newuser
});
});
module.exports = router;
However, when I visit localhost/newuser, I get the following error: TypeError: undefined is not a function. This error is being thrown in index.js on the line I marked with 5 asterisks above.
You are defining a constructor named User() and exporting it. But, then when you require('../lib/user'), you get the constructor function, but you never construct a new object with it so you don't actually have an object of type User, you just have the constructor and thus there is no method addUser() on the constructor.
Instead of this:
var User = require('../lib/user');
you can call the constructor function like this:
var u = require('../lib/user');
var User = new u();
Or, if you never need to make another one, you can do it all in one line:
var User = new (require('../lib/user'))();
Another way would be to change your User.js class to return something on these lines...
function User(){};
User.prototype.addUser = function(){
//Do stuff
return 0;
};
module.exports = new User();

Categories

Resources