This is my mongoDb connection
var mongoose = require('mongoose');
// Connection URL
var db = 'mongodb://localhost:27017/employeeDetails';
// Use connect method to connect to the Server
mongoose.connect(db, function (error) {
if (error) {
console.log(error);
}
});
var Schema = mongoose.Schema;
var Employee_Schema = new Schema({
EmployeeName: String,
Designation: String,
Project: String,
Skills:String
});
var Employee = mongoose.model('employees', Employee_Schema);
module.exports=Employee;
This is my api code (express.js)
var express=require('express');
var router=express.Router();
var Employee=require('../database/dataFile');
router.get('/',function(req,resp,next){
Employee.find({},function(err,docs){
resp.send(docs);
})
});
router.post('/create',function(req, resp, next){
var employee_collection =Employee.collection(Employee);
employee_collection.insert(req.body, function(err, doc) {
if(err) throw err;
console.log(doc);
res.json(doc);
});
});
module.exports=router;
This is my $http.post
create(employee: Employee) {
return this.http.post('http://localhost:4500/api/create', employee).map((response: Response) => response.json());
}
I always get
Failed to load resource: the server responded with a status of 500
(Internal Server Error)
FYI: $http.get works fine. It fetches data from MongoDb. The following hit the get method in api
getEmployeeList() {
return this.http.get('http://localhost:4500/api');
}
Please note I am taking example from here
This tutorial does not have Post functionality and I am trying to implement.
There Is A problem with the query, If you want to fetch the collection use:
mongoose.getCollection(<collection name>), But here you are calling the collection function on a model object, not the mongoose one.
Instead, I Would recommend using .create directly:
Employee.create(req.body, function(err,result){
if(err){throw Error(err)}
return res.json(result);
})
Related
I have been trying W3schools tutorial on nodeJS with MongoDB.
When I try to implement this example in a nodeJS environment and invoke the function with an AJAX call, I got the error below:
TypeError: db.collection is not a function
at c:\Users\user\Desktop\Web Project\WebService.JS:79:14
at args.push (c:\Users\user\node_modules\mongodb\lib\utils.js:431:72)
at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:254:5
at connectCallback (c:\Users\user\node_modules\mongodb\lib\mongo_client.js:933:5)
at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:794:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
Please find below my implemented code:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mytestingdb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("customers").findOne({}, function(err, result) {
if (err) throw err;
console.log(result.name);
db.close();
});
});
Note that the error occurs whenever the execution hits:
db.collection("customers").findOne({}, function(err, result) {}
Also, note (in case it matters) that I have installed the latest MongoDB package for node JS (npm install mongodb), and the MongoDB version is MongoDB Enterprise 3.4.4, with MongoDB Node.js driver v3.0.0-rc0.
For people on version 3.0 of the MongoDB native NodeJS driver:
(This is applicable to people with "mongodb": "^3.0.0-rc0", or a later version in package.json, that want to keep using the latest version.)
In version 2.x of the MongoDB native NodeJS driver you would get the database object as an argument to the connect callback:
MongoClient.connect('mongodb://localhost:27017/mytestingdb', (err, db) => {
// Database returned
});
According to the changelog for 3.0 you now get a client object containing the database object instead:
MongoClient.connect('mongodb://localhost:27017', (err, client) => {
// Client returned
var db = client.db('mytestingdb');
});
The close() method has also been moved to the client. The code in the question can therefore be translated to:
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('mytestingdb');
db.collection('customers').findOne({}, function (findErr, result) {
if (findErr) throw findErr;
console.log(result.name);
client.close();
});
});
I encountered the same thing. In package.json, change mongodb line to "mongodb": "^2.2.33". You will need to uninstall mongodb npm by removing MongoDB Driver/ node_modules or etc , then install npm to install this version.
This resolved the issue for me. Seems to be a bug or docs need to be updated.
For those that want to continue using version ^3.0.1 be aware of the changes to how you use the MongoClient.connect() method. The callback doesn't return db instead it returns client, against which there is a function called db(dbname) that you must invoke to get the db instance you are looking for.
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
MongoClient.connect(url (err, client) => {
if(err) throw err;
let database = client.db('databaseName');
database.collection('name').find()
.toArray((err, results) => {
if(err) throw err;
results.forEach((value)=>{
console.log(value.name);
});
})
})
The only problem with your code is that you are accessing the object that's holding the database handler. You must access the database directly (see database variable above). This code will return your database in an array and then it loops through it and logs the name for everyone in the database.
Piggy backing on #MikkaS answer for Mongo Client v3.x, I just needed the async / await format, which looks slightly modified as this:
const myFunc = async () => {
// Prepping here...
// Connect
let client = await MongoClient.connect('mongodb://localhost');
let db = await client.db();
// Run the query
let cursor = await db.collection('customers').find({});
// Do whatever you want on the result.
}
I did a little experimenting to see if I could keep the database name as part of the url. I prefer the promise syntax but it should still work for the callback syntax. Notice below that client.db() is called without passing any parameters.
MongoClient.connect(
'mongodb://localhost:27017/mytestingdb',
{ useNewUrlParser: true}
)
.then(client => {
// The database name is part of the url. client.db() seems
// to know that and works even without a parameter that
// relays the db name.
let db = client.db();
console.log('the current database is: ' + db.s.databaseName);
// client.close() if you want to
})
.catch(err => console.log(err));
My package.json lists monbodb ^3.2.5.
The 'useNewUrlParser' option is not required if you're willing to deal with a deprecation warning. But it is wise to use at this point until version 4 comes out where presumably the new driver will be the default and you won't need the option anymore.
It used to work with the older versions of MongoDb client ~ 2.2.33
Option 1: So you can either use the older version
npm uninstall mongodb --save
npm install mongodb#2.2.33 --save
Option 2: Keep using the newer version (3.0 and above) and modify the code a little bit.
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client){
if(err) throw err;
let db = client.db('myTestingDb');
db.collection('customers').find().toArray(function(err, result){
if(err) throw err;
console.log(result);
client.close();
});
});
I solved it easily via running these codes:
npm uninstall mongodb --save
npm install mongodb#2.2.33 --save
Happy Coding!
If someone is still trying how to resolve this error, I have done this like below.
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'mytestingdb';
const retrieveCustomers = (db, callback)=>{
// Get the customers collection
const collection = db.collection('customers');
// Find some customers
collection.find({}).toArray((err, customers) =>{
if(err) throw err;
console.log("Found the following records");
console.log(customers)
callback(customers);
});
}
const retrieveCustomer = (db, callback)=>{
// Get the customers collection
const collection = db.collection('customers');
// Find some customers
collection.find({'name': 'mahendra'}).toArray((err, customers) =>{
if(err) throw err;
console.log("Found the following records");
console.log(customers)
callback(customers);
});
}
const insertCustomers = (db, callback)=> {
// Get the customers collection
const collection = db.collection('customers');
const dataArray = [{name : 'mahendra'}, {name :'divit'}, {name : 'aryan'} ];
// Insert some customers
collection.insertMany(dataArray, (err, result)=> {
if(err) throw err;
console.log("Inserted 3 customers into the collection");
callback(result);
});
}
// Use connect method to connect to the server
MongoClient.connect(url,{ useUnifiedTopology: true }, (err, client) => {
console.log("Connected successfully to server");
const db = client.db(dbName);
insertCustomers(db, ()=> {
retrieveCustomers(db, ()=> {
retrieveCustomer(db, ()=> {
client.close();
});
});
});
});
I have MongoDB shell version v3.6.4, below code use mongoclient, It's good for me:
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var url = 'mongodb://localhost:27017/video';
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, client)
{
assert.equal(null, err);
console.log("Successfully connected to server");
var db = client.db('video');
// Find some documents in our collection
db.collection('movies').find({}).toArray(function(err, docs) {
// Print the documents returned
docs.forEach(function(doc) {
console.log(doc.title);
});
// Close the DB
client.close();
});
// Declare success
console.log("Called find()");
});
MongoDB queries return a cursor to an array stored in memory. To access that array's result you must call .toArray() at the end of the query.
db.collection("customers").find({}).toArray()
Late answer but maybe someone will need it in future
we can create async function which one will return our collection and db instances
const dBInstances = async () => {
const collection = await db
.then((client) => {
const db = client.db();
const collection = db.collection("AGGREGATION");
return { collection: collection, db: db };
})
.catch((err) => {
console.log(`Data base instances error ${err}`);
});
return collection;
};
and after we can use result of execution dBInstances() by this way i used JS destructurisation in example below
const test = async (req, res) => {
const { collection, db } = await dBInstances();
console.log(collection);
console.log(db);
};
now we have separated access to our db and collection.
Recently I had the same issue, I finally resolved it using MongoDB official website documentation and sample codes.
My MongoDB client version is "mongodb": "^4.4.1" and I managed to insert a document finally without needing to downgrade my MongoDB package according to the approved answer which seems to be obsolete.
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.
const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db("insertDB");
const haiku = database.collection("haiku");
// create a document to insert
const doc = {
title: "Record of a Shriveled Datum",
content: "No bytes, no problem. Just insert a document, in MongoDB",
}
const result = await haiku.insertOne(doc);
console.log(`A document was inserted with the _id: ${result.insertedId}`);
} finally {
await client.close();
}
}
run().catch(console.dir);
I'm trying to create web services using node.js from an sql server database,in the frontend when i call those 2 webservices simultaneously it throws an error Global connection already exists. Call sql.close() first .
Any Solution ?
var express = require('express');
var router = express.Router();
var sql = require("mssql");
router.get('/Plant/:server/:user/:password/:database', function(req, res, next) {
user = req.params.user;
password = req.params.password;
server = req.params.server;
database = req.params.database;
// config for your database
var config = {
user: user,
password: password,
server: server,
database:database
};
sql.connect(config, function (err) {
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("SELECT distinct PlantName FROM MachineryStateTable"
, function (err, recordset) {
if (err) console.log(err)
else {
for(i=0;i<recordset.recordsets.length;i++) {
res.send(recordset.recordsets[i])
}
}
sql.close();
});
});
});
router.get('/Dep/:server/:user/:password/:database/:plantname', function(req, res, next) {
user = req.params.user;
password = req.params.password;
server = req.params.server;
database = req.params.database;
plantname = req.params.plantname;
// config for your database
var config = {
user: user,
password: password,
server: server,
database:database
};
sql.connect(config, function (err) {
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("SELECT distinct DepName FROM MachineryStateTable where PlantName= '"+plantname+"'"
, function (err, recordset) {
if (err) console.log(err)
else {
for(i=0;i<recordset.recordsets.length;i++) {
res.send(recordset.recordsets[i])
}
sql.close();
}
});
});
});
module.exports = router;
You have to create a poolConnection
try this:
new sql.ConnectionPool(config).connect().then(pool => {
return pool.request().query("SELECT * FROM MyTable")
}).then(result => {
let rows = result.recordset
res.setHeader('Access-Control-Allow-Origin', '*')
res.status(200).json(rows);
sql.close();
}).catch(err => {
res.status(500).send({ message: `${err}`})
sql.close();
});
From the documentation, close method should be used on the connection, and not on the required module,
So should be used like
var connection = new sql.Connection({
user: '...',
password: '...',
server: 'localhost',
database: '...'
});
connection.close().
Also couple of suggestions,
1. putting res.send in a loop isn't a good idea, You could reply back the entire recordsets or do operations over it, store the resultant in a variable and send that back.
2. Try using promises, instead of callbacks, it would make the flow neater
You must use ConnectionPool.
Next function returns a recordset with my query results.
async function execute2(query) {
return new Promise((resolve, reject) => {
new sql.ConnectionPool(dbConfig).connect().then(pool => {
return pool.request().query(query)
}).then(result => {
resolve(result.recordset);
sql.close();
}).catch(err => {
reject(err)
sql.close();
});
});
}
Works fine in my code!
if this problem still bother you, then change the core api.
go to node_modules\mssql\lib\base.js
at line 1723, add below code before if condition
globalConnection = null
In case someone comes here trying to find out how to use SQL Server pool connection with parameters:
var executeQuery = function(res,query,parameters){
new sql.ConnectionPool(sqlConfig).connect().then(pool =>{
// create request object
var request = new sql.Request(pool);
// Add parameters
parameters.forEach(function(p) {
request.input(p.name, p.sqltype, p.value);
});
// query to the database
request.query(query,function(err,result){
res.send(result);
sql.close();
});
})
}
Don't read their documentation, I don't think it was written by someone that actually uses the library :) Also don't pay any attention to the names of things, a 'ConnectionPool' doesn't seem to actually be a connection pool of any sort. If you try and create more than one connection from a pool, you will get an error. This is the code that I eventually got working:
const sql = require('mssql');
let pool = new sql.ConnectionPool(config); // some object that lets you connect ONCE
let cnn = await pool.connect(); // create single allowed connection on this 'pool'
let result = await cnn.request().query(query);
console.log('result:', result);
cnn.close(); // close your connection
return result;
This code can be run multiple times in parallel and seems to create multiple connections and correctly close them.
i am using nodejs as server, I am sending parameters to mongodb and saving it in database after that i am fetching it from database. But when i try to fetch the data i can't able to see the current data in nodejs terminal ,but it will be present in database. Again if i send the other data i will able to see the previous data but not the current data which i have sent now. I think my server is calling find function before save function. what should i do to make my save function to complete its task and then it should call the find function.
this mongodb code
import mongoose from 'mongoose';
var Schema = mongoose.Schema;
//connect to a MongoDB database
var db = mongoose.connect('mongodb://127.0.0.1:27017/student');
mongoose.connect('connected', function() {
console.log("database connected successfully")
});
var userSchema = new Schema({
Name: {
type: String,
required: true
},
Age: {
type: Number,
required: true
}
}, {
collection: ('studentcollection2')
});
var User = mongoose.model('User', userSchema);
function createStudent(name, age) {
var list = new User({
Name: name,
Age: age
});
list.save(function(err) {
if (err) throw err;
console.log("SUCCESSFUL");
});
}
function listStudent() {
User.find({}, function(err, studentcollection2) {
if (err) throw err;
console.log(studentcollection2);
});
}
exports.createStudent = createStudent; //module.exports = User;
exports.listStudent = listStudent;
this is my server code
import config from './config';
import express from 'express';
const server = express();
import mongodbInterface from './mongodbInterface';
server.set('view engine', 'ejs');
server.get('/', (req, res) => {
res.render('index', {
content: '...'
})
});
console.log(typeof mongodbInterface.createStudent);
mongodbInterface.createStudent("a9", 112);
mongodbInterface.listStudent();
server.use(express.static('public'));
server.listen(config.port, () => {
console.info('express listening on port', config.port);
});
I haven't run your code, but I imagine it's coming down to these two lines:
mongodbInterface.createStudent("a9", 112);
mongodbInterface.listStudent();
Both of these statements call asynchronous functionality. That is to say that when you call createStudent("a9", 112);, that functionality will run asynchronously in the background, and Node will continue to call listStudent(); straight away. Therefore, your createStudent method may not have written the data to the database by the time your listStudent function is run.
To solve this, you need to make use of callback functions to only retrieve the data once it's actually been saved. For example, you could do the following:
function createStudent(name, age, cb) {
var list = new User({
Name: name,
Age: age
});
list.save(function(err) {
if (err) return cb(err);
return cb();
});
}
function listStudent(cb) {
User.find({}, function(err, studentcollection2) {
if (err) return cb(err);
return cb(null, studentCollection2);
});
}
Then, in your server code:
mongodbInterface.createStudent("a9", 112, function(err) {
if (err) throw err;
mongodbInterface.listStudent(function(err, students) {
console.log(students); // You should see the newly saved student here
});
});
I'd recommend reading more about Node.js callbacks here - they are really core to the usage of Node.js.
The mongo methods are async so the data will write whenever it's ready. Use a callback function, promise or async/await to wait for the result without blocking the event loop and control order of execution.
I am new to node.js and am just trying to understand the asynchronous nature of how this stuff works.
Ok this is a very simple form submission.The model looks like the below:-
var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var PostSchema=new Schema({
title:{type:String,required:true},
post:String,
});
var PostModel=mongoose.model('blogpost',PostSchema);
module.exports=PostModel;
and then the route handler is as below:-
app.post("/submitpost",function(req,res){
var title=req.body.title;
var post=req.body.post;
var thepost=new PostModel({title:title,post:post});
thepost.save(function(err,data){
if(err)throw err;
console.log(data);
})
console.log("title is "+title);
console.log("post is "+post);
res.send("saved");
});
Now suppose the validation fails during "thepost.save(callback)" , i would want to show an error page rather than "saved" . How would i do that?
Simply move the rendering of the response into the callback:
app.post("/submitpost",function(req,res){
var title=req.body.title;
var post=req.body.post;
var thepost=new PostModel({title:title,post:post});
thepost.save(function(err,data){
if(err) {
res.render('errorPage');
} else {
console.log(data);
console.log("title is "+title);
console.log("post is "+post);
res.send("saved");
}
})
});
Through ajax request I have get the data form client and save it in mongodb database (mongoose) through save query .Now I want to know how to find data and display it new page.
I have get the data from client and save it in database. Now I want that when callback function calls it find data from the database and display it in new page using response.redirect.Please guide me.
$("#saveChanges5").live('click',function(){
var sendingObj = {
regOperation: $("#area_operation").val()
,regFieldAct: $("#field_activity").val()
,regOther: $("#other_details").val()
};
$.ajax({
url:'/WorkDetails'
,type:'post'
,data: sendingObj
,success:function(){
alert('Successfully saved')
},
error: function(){
alert("Saving Failed")
}
})
});
app.post("/WorkDetails",function(req ,res){
console.log(req.body);
saveWorkDetails(req.body.regOperation ,req.body.regFieldAct ,req.body.regOther ,function(){
res.send("");//here i want to add new code
});
});
function saveWorkDetails(area_operation ,field_activity ,other_details , callback){
console.log("save CALLED");
var receivedObj = new WorkDetailInfo({
area_operation:area_operation ,
field_activity:field_activity ,
other_details:other_details
});
console.log(receivedObj);
receivedObj.save(function(err){
console.log("inside Save ");
if(err){
//res.send(err);
console.log(err);
}
else{
callback();
}
});
}
You can make use of narwhal-mongodb APIs
Following is the example usage:
var MongoDB = require("mongodb");
var db = new MongoDB.Mongo().getDB("mydb");
var colls = db.getCollectionNames();
colls.forEach(function(el) { print(el); });
var coll = db.getCollection("testCollection");