Display the data onto webpage retrieved from mongodb using node.js - javascript

Heres my problem. Might be a bit trivial. I am using node.js to write a form which has radio buttons, drop down boxes. I have been able to save data and also retrieve it successfully but I am not able to write it onto web page. What is the correct way to write the data onto a page

You can do this pretty easily with express and mongoose. First you would connect to mongoDB using mongoose, and then set up some of the variables used to interact with mongoDB from mongoose (i.e. mongoose.scheme & mongoose.model), and finally you simply send your mongoDB data to a web page through express's res.render function:
mongoose.connect('mongodb://localhost/test', function(err){
if(!err){
console.log('connected to mongoDB');
} else{
throw err;
}
});
var Schema = mongoose.Schema,
ObjectID = Schema.ObjectID;
var Person = new Schema({
name : String
});
var Person = mongoose.model('Person', Person);
app.get('/', function(req, res){
Person.find({}, function(err, docs){
res.render('index', { docs: docs});
});
});
After sending the data, you can simply reference the 'docs' variable in your web page. Express automatically uses the Jade framework. In Jade you could do something like list all the names of the people in your database:
- if(docs.length)
each person in docs
p #{person.name}
- else
p No one is in your database!

Related

Mongodb does not save a document

I am trying to store some data from an HTML formulary. I send the data using the HTTP POST method and I received them using Express framework in Node.js. The data arrives and it seems to work, but when I try to store them into MongoDB using Mongoose, the database is created but no data is stored when I execute DB.sis_dictionary.find()
I've tried to build different types of schemas and models, but none seems to work. And I get no error from Node.js, it seems to be working, but the MongoDB database does not store anything.
const Mongoose = require('mongoose');
Mongoose.connect('mongodb://localhost:27017/sis_dictionary', {useNewUrlParser: true});
const Schema = Mongoose.Schema;
const wordSchema = new Schema({
word: String
})
const Word = Mongoose.model('Word', wordSchema);
app.post('/saveWord', (req, res) => {
var word = new Word({word: String(req.body)});
word.save(function(err){
if(err) {
return console.error(err);
} else {
console.log("STATUS: WORKING");
}
})
console.log(req.body);
})
server.listen(3000);
console.log("SERVER STARTUP SUCCESS");
In the console, I get the message: "STATUS: WORKING".
sis_ditionary is your DB name and Words should be your collection name. As mongoose automatically creates a plural name for collection from a model if model name not specified when creating from a schema
db.collection.find() is a command to find a collection data when using mongo-shell. Run below command to get data:
use sis_dictionary
db.Words.find()
To beautify result use pretty method
db.Words.find().pretty()
First command will select DB and second command list collection data.
So when you execute db.sis_dictionary.find() it won't work because sis_dictinary is your DB name.
Nodejs way with 'mongoose'
//Model.find({});
Word.find({});
Also, check this line var word = new Word({word: String(req.body)});
What does req.body have? If req.body is {word:"example word"} then you directly pass req.body to modal constructor ie new Word(req.body);
According to your database URL, mongodb://localhost:27017/sis_dictionary, sis_dictionary is the database name.
And according to your mongoose model, Word is your collection name.
When you save a document, it saves under a collection. So you have to make a query under the collections.
So when you try to get data using DB.sis_dictionary.find(), definitely it won't work.
Your query should be like db.collection.find()
Use the following query,
use sis_dictionary
db.words.find()
// for better view
db.words.find().pretty()
For more please check the documentation.
Thank you everybody. You were all right, it was a problem related to my collections names. db.words.find().pretty() worked perfectly!The problem is solved.

Impossible to create users (or custom-based roles) in Mongo on server NodeJS

I am trying to create users on my database directly from our Express server, using Mongo 3.4 for the database. Here is the code for the server for now:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://mongo:27017/myDb';
var dbvotes = "collection1";
var dbusers = "collection2";
//Functions for users
app.post('/newUser', function(req, res, db) {
MongoClient.connect(url, function(err, db){
//Ecriture dans la base user
db.collection(dbusers).insertOne( {
"name" : req.body.name,
"surname" : req.body.surname,
"username" : username,
"password" : "pasadmin",
});
//Creation of the user in the DB
db.createUser( { 'user': username, 'pwd': "pasadmin", roles: [] });
db.close();
});
console.log("Inserted a new user in the database.");
res.send("User added. Click precedent to add a new user.");
});
However, whenever the client tries to insert a new user, it is effectively created in the user collections, but not as a user of the database as I get the following error: TypeError: db.createUser is not a function
web_1 | at /app/app.js:47:6.
I have tried to user db.addUser instead, however, this is deprecated since Mongo 2.6 and not working either, and db.adminCommand serves the same error, db.adminCommand is not a function. Before that, I struggled to create custom roles in the database with Node and decided to do it via the Mongo shell as well, but it's not an option when it comes to adding user 1 by 1 in the database.
When I use these functions in the Mongo shell, the commands are working, so I suppose it comes from the way I implemented Mongo within the server (via Docker), or due to some limitations with Javascript. Any idea what could it be?
Thanks in advance to the community!
The proper command would be:
db.addUser( username, password, { roles: [ role ] } );
Where role is some MongoDB role. More info can be found from the source file. It can also be an object in the formation of { role: <string>, db: <string> }, where role is a MongoDB role and db is the string name of the database.
You can also use db.admin().addUser. This would be the logical choice if the user has access to multiple databases or you want a central location of your users.
However, I can't imagine it's a good idea to add system users from your application unless you're developing an actual administrative tool. Normal "users" added to a database would be in your own users collection. A system user is someone who has direct access to your database.

Upload and retrieve text/pdf/img files on mongodb using mongoose in a MEAN stack application

I've been trying to write a piece of code in which the user creates a dynamic url, uploads a file by clicking on a button on the page, and the user can also download the same file in the same format when he/she visits the same url again. The concept is very much like cl1p with a difference of file in place of text.
I worked out a lot of answers on SO but I cannot find any help on how to accept the file in angular controller, and pass to the back end(node.js code), where the file can be saved on mongodb database using mongoose, and the same file can be retrieved from the mongodb database. Also, I wish to save the complete file in database, not just the path/destination of file.
Please help.
As of now, all I have is -
<div ng-controller="main">
<input type="file" name="myFile" id="file" />
<button type="submit">Upload</button>
</div>
PS: Do not ask me to use GridFS, it is useful in cases when data exceeds 16MB, my file size won't exceed 2~3MB.
I'm not too familiar with angular. But, I can give some hint in backend.
model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
image: {data: Buffer, contentType: String},
.
.
});
module.exports = mongoose.model('Model', schema);
route.js
var Model = require('path/to/model');
// POST: called by uploading form
router.post('/add', function (req, res, next) {
var model = new Model();
fs.readFile(req.body.myFile, function (err, data) {
model.image.data = data;
// get extension
model.image.contentType = req.body.myFile.split('.').pop();
.
.
model.save(function (err, model) {
if(err) throw err;
res.status(201).json(model);
});
});
});
// GET image by model id: subsequence retrieval
router.get('/:id/image', function (req, res, next) {
var modelId = req.params.id;
Model.findById(modelId, function (err, model) {
res.contentType(model.image.contentType);
res.json(model.image.data);
});
});
i used https://github.com/expressjs/multer
worked for me, especially if you want to store it anywhere else but a DB later on.
And https://github.com/nervgh/angular-file-upload on the client side if you use Angular 1.

mongodb data finds commands on cmd

I am learning node and mongodb
My app is working fine (Its is online tutorial app)
I have two Question
// define model =================
var Todo = mongoose.model('Todo', {
text : String
});
// create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {
// create a todo, information comes from AJAX request from Angular
Todo.create({
text : req.body.text,
done : false
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
I hope you understand my code (Its todo adding app)
1) Is 'Todo' is collection in mongoDB ?
I typed on cmd db.collection.find() but nothing result ? , Which command i use on cmd to see data here
2) Can I open DB data storage file in my editor with any tool ?
Online tutorial app link
Thanks
First you have to select the database.
use database-name
You can find the list of collections in database using the following command.
show collections
You can find the list for databases using the following command
show dbs
Then use the db.collection.find() command.
use help command to find list of commands.

node + express + mongoose query authentification

Im building a simple web app app in express, and I'm a bit stuck in the authentification for my sessions, im going to validate everything in the client with backbone and regExp eventually when i start building the front end of the app. no basycally i have an issue with the query in mongoose returning a mongoose document object. I've looked up a couple of solutions, in the query you can use a .lean() to get an object, or grab the return from the query and apply a .toObject(), that all works fine and dandy, however when i try and authenticate the value of the key with a string it returns false. i'll post an example code, its not exactly what i've got, but its close enough to get the point across.
this would be an example of my models file
var User = new Schema({}, { strict: false });
User.method('authenticate', function(plainText) {
var object = this.toObject();
return plainText == object.password; });
mongoose.model('User', User);
mongoose.connect( definitions.dbConnect );
and in my app file i would have something like
app.get('/session', routes.showLogin);
app.post('/session/new', routes.login);
and in my routes file id have something like
exports.login = function(req, res){
var userQuery = new RegExp(req.body.username , 'i');
var passwordQuery = new RegExp(req.body.password, 'i');
var Query = User.find();
Query.findOne().where('username', userQuery).exec(function(err, user){
if(user && user.authenticate((req.body.password))){
req.session.userId = user._id;
}else{
res.redirect('/session');
}
});
},
Any ideas would be appreciated, its probably very silly... : /
Thanks in advanced!
YEah robert klep was right on the money, After i seearched the mongoose Documentation and the mongodb docs as well, it became clear that queries return a mongo document object, in terms should be converted to the same object or variable types for opperands to work.

Categories