I am very new to mongodb, literally just installed yesterday. I created a collection programmatically, and now am trying to insert a document into the already created collection.
here's what I have:
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
db.socialPosts.insert( { title: "My First Post", description: "This is my first post desc" } )
console.log("success")
db.close();
});
});
the name of the collection is socialPosts, and I am just trying to insert a doc into it. The error it is throwing is:
TypeError: Cannot read property 'insert' of undefined
how do i fix this?
based on the answers above, and some research online, I have come across this solution:
client.connect().then (() => {
const database = client.db("myFirstDatabase");
const socialPosts = database.collection("socialPosts");
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
const doc = { title: postTitle, description: postDescription, instagramLink: instagramLink };
socialPosts.insertOne(doc)
db.close();
});
});
this works seamlessly :)
Related
I am trying to create a website and found out that Javascript does not have any way to contact a database. I did some research and found out about node.js. I created a node.js file and a small portion of my code is:
var mysql;
var con;
function initialise() {
mysql = require('mysql');
con = mysql.createConnection({
host: "name of the server the database is on",
user: "name of user that has can add and delete stuff to the database",
password: "password for the user",
database: "name of the database"
});
con.connect(function(err) {
if (err) throw err;
});
}
function getCoach(sql, con) {
return new Promise((resolve, reject) => {
con.query(sql, function (err, rows, fields) {
if (err) {
reject = (err);
throw err;
}
resolve(rows);
});
});
}
async function info() {
con.connect(function(err) {
if (err) throw err;
});
const results2 = await getCoach("SELECT username, password FROM coach", con);
return results2;
con.end();
}
I need the require('mysql') inorder to connect with the database. I tested it out and I can get a connection with the database on this file, but when I called a function in the node.js file through Javascript I got an error saying that require() is not defined. I did some research and found many things like Browserify to try and fix this issue, but nothing is working. How do I remove the error so that I can connect to the database that I created through JavaScript. What am I missing and is there a better way of doing this?
Try including your require statement outside the function like this:
const mysql = require("mysql")
I'm using nodejs 10.26 + express 3.5 + node-mysql 2.1.1 +
MySQL-Server Version: 5.6.16.
I got 4 DELETE's and want only 1 Database Request, so i connected the DELETE commands with a ";"... but it fails always.
var sql_string = "DELETE FROM user_tables WHERE name = 'Testbase';";
sql_string += "DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase';";
connection.query(sql_string, function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
It throws this error:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';DELETE FR' at line 1
But if i paste this SQL in PhpMyAdmin it is always successful...
If i write it in single query's its succeed, too.
connection.query("DELETE FROM user_tables WHERE name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
});
});
});
Thanks for help!
I guess you are using node-mysql. (but should also work for node-mysql2)
The docs says:
Support for multiple statements is disabled for security reasons (it
allows for SQL injection attacks if values are not properly escaped).
Multiple statement queries
To use this feature you have to enable it for your connection:
var connection = mysql.createConnection({multipleStatements: true});
Once enabled, you can execute queries with multiple statements by separating each statement with a semi-colon ;. Result will be an array for each statement.
Example
connection.query('SELECT ?; SELECT ?', [1, 2], function(err, results) {
if (err) throw err;
// `results` is an array with one element for every statement in the query:
console.log(results[0]); // [{1: 1}]
console.log(results[1]); // [{2: 2}]
});
So if you have enabled the multipleStatements, your first code should work.
Using "multiplestatements: true" like shown below worked for me
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: '',
multipleStatements: true
});
connection.connect();
var sql = "CREATE TABLE test(id INT DEFAULT 1, name VARCHAR(50));ALTER TABLE test ADD age VARCHAR(10);";
connection.query(sql, function(error, results, fields) {
if (error) {
throw error;
}
});
To Fetch Data from DB(SQL), the following function would work accurately
router.get('/', function messageFunction(req, res){
//res.send('Hi Dear Rasikh, Welcome to Test Page.') //=> One Way
dbConn.query('SELECT COUNT(name) as counted, name, last_name, phone, email from students',
function (err, rows, fields) { // another Way
if (err) throw err
dbConn.query('SELECT name, author from books',
function (err, rowsBook, fields) { // another Way
if (err) throw err
// console.log('The counted is: ', rows[0].counted); //=> Display in console
// res.send('Hi Dear Rasikh, Welcome to Test Page.'+ rows[0].counted) //=> Display in blank page
res.render('main/index',{data:rows, myData:rowsBook});
})
});
});
I have a schema called "Project" and when I delete its data in my app.js the length of the schema stay same.
I delete it in the following route:
router.get("/myprojects/:id/remove", function(req, res){
Project.findByIdAndRemove(req.params.id, function(err){
if(err){
console.log(err);
}else{
res.redirect("/myprojects");
}
});
});
but when i get the length of the Project in another page, even after deleting everything, the length doesn't change.
<%= user.projects.length %>
P.S. I have deleted the whole schema in Mongo but the length still shows the same number!!
Better you try like below
router.get("/myprojects/:id/remove", function (req, res) {
let Project = require('./path/to/Project.js');
Project.remove({ "_id": req.params.id }).exec(function (err, RemoveStatus) {
if (err) {
console.log(err);
} else {
console.log("Remove Status---->", RemoveStatus);
res.redirect("/myprojects");
}
});
});
It have always worked for me.
Task I have is to make a array of i.e. dishes that logged user is selecting as his favourite. Problem is that instead of one array of objectIDs i.e. dishes:[123456,5678910], i get two separate objects for same user with only one dish id in the array.
I presume that problem is in my schema, so can someone give me an idea?
var favoriteSchema = new Schema({
timestamps: true,
dishes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Dish'
}],
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
Edit>> My post method as demanded
.post(Verify.verifyOrdinaryUser, function (req, res, next) {
Favorites.create(req.body, function (err, favorite) {
if (err) throw err;
console.log('favorite created!');
var id = favorite._id;
favorite.postedBy = req.decoded._doc._id;
favorite.dishes.push(req.body);
favorite.save(function (err, favorite) {
if (err) throw err;
console.log('Updated Favorites!');
res.json(favorite);
});
});
Your post method is fine for the first time you want to add a favorite dish. The next time you add a dish for the same user you should call
Favorites.findOne({postedBy: req.decoded._doc._id}, function (err, favorite) {
favorite.dishes.push(req.body);
favorite.save(function (err, favorite) {
if (err) throw err;
res.json(favorite);
});
})
I am building a server with node.js (express) and mysql felix.
my problem is that sometime i have a query that will return a duplicate error.
I have tried everything on mind to try and catch this error without luck, the program crashes.
This is my code:
this.addReservation = function(req, res, next) {
var json = JSON.parse(req.body['reservation']);
var post = {user1: json.player1, user2: json.player2, courtId: json.id, hour: json.hour, date: json.date};
var giveback = {u1_first: req.user.firstName, u1_last: req.user.lastName, user1: json.player1, user2: json.player2};
connection.query('insert into ordering set ?', post, function(err, result){
if (err){
throw err;
return res.send(500);
}
else
return res.json({res: giveback})
//return res.send(200);
});
};
now i have tried wrapping this query with try and catch. didn't help.
i tried to enter this row:
connection.on('error', function() {console.log();}); didn't help neither.
i tried putting this line in other places still not helping.
the error that is thrown in my console is: Error: ER_DUP_ENTRY.
what am i doing wrong? should i use "on" on something different than 'error'?
that only thing that helped me is:
process.on('uncaughtException', function(err) {
// handle the error safely
console.log(err);
});
but this is very bad as i do know the error that is caused and i wish to deal with it so this is a very bad solution for me.
please help me thanks. i am using mysql felix library.
this.addReservation = function(req, res, next) {
var json = JSON.parse(req.body['reservation']);
var post = {user1: json.player1, user2: json.player2, courtId: json.id, hour: json.hour, date: json.date};
var giveback = {u1_first: req.user.firstName, u1_last: req.user.lastName, user1: json.player1, user2: json.player2};
connection.query('insert into ordering set ?', post, function(err, result){
if (err){
console.log('exact name of error thrown '+err);
return res.send(500);
}
else
return res.json({res: giveback})
//return res.send(200);
});
};