mongodb data finds commands on cmd - javascript

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.

Related

How to insert new MySQL JSON TYPES object from the browser in NODE.JS

I had this question about sql, json, and nodeJS. Is there a way I can insert something like this through node.js (Here's the link from oracle official website where I was referring to: enter link description here)
INSERT INTO t1 VALUES('{"key1": "value1", "key2": "value2"}');
I'm trying to come up with a better data structure for my project. I've been using simple sql queries just like the ones from W3SCHOOL, but the more I keep working on my project, the more I realize that using JSON DATA TYPE would be more appropriate.
And here's how I was trying to insert an object from my server.js file, but without success!!!
app.get('/demo/add/', (req, res) => {
const { content, author, ID} = req.query;
const sql = `insert into demo values({'${content}':'content', '${author}':'author', '${ID}':3})`
con.query(sql, (err, results) =>{
if(err){
return res.send(err)
} else{
return res.send('Successfully added a new content!!')
}
})
});
Previously, I had been using this method: http://localhost:4000/demo/add?key1=value&key2=value2... for simple query, but for now, I'm kind of stuck!!
Thank you in advance
I used json_extract() method to retrieve data from sql tables, and that's pretty much what my struggle was about.

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.

MongoDB / Express - How to switch database after connecting via connect()

I am using express to connect to my mongoDB:
mongodb.MongoClient.connect(mongourl, function(err, database) {
// How would one switch to another database here?
});
I have to connect to the admin database in the first place. After the conenction has been established, i would like to switch the database.
Although i have searched through the official documentation, i was unable to find something that fits my needs.
I am aware of the MongoClient::open() method, but i would like to stick to connect().
Any help is appreciated.
You can switch to another database like so:
mongodb.MongoClient.connect(mongourl, function(err, database) {
// switch to another database
database = database.db(DATABASE_NAME);
...
});
(docs)
EDIT: for clarification: this also allows you to open multiple databases over the same connection:
mongodb.MongoClient.connect(mongourl, function(err, database) {
// open another database over the same connection
var database2 = database.db(DATABASE_NAME);
// now you can use both `database` and `database2`
...
});
You just have to call MongoClient.connect once again, because there is one connection per database. That means, you cannot change the database of an existing connection. You have to connect a second time:
mongodb.MongoClient.connect(mongourl, function(err, database) {
mongodb.MongoClient.connect(mongourl_to_other_database, function(err, database2) {
// use database or database2
});
});

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

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!

Categories