I am making an app using nodejs and I am learning the mongodb, but I do it just like the docs. but the command prompt shows:
events.js:141
throw er; // Unhandled 'error' event
^
Error: Trying to open unclosed connection.
at NativeConnection.Connection.open (C:\Users\html5col\Desktop\express\node_modules\mongoose\lib\connection.js:236:15)
at Mongoose.connect (C:\Users\html5col\Desktop\express\node_modules\mongoose\lib\index.js:241:47)
at Object.<anonymous> (C:\Users\html5col\Desktop\express\app.js:19:10)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
//my app.js file
var url = 'mongodb://fran84:fran#ds013250.mlab.com:13250/ndeme';
//ABOVE URL USING MLAB SERVICE
var mongoose = require('mongoose');
mongoose.connect(url);
console.log('isonerror');
var mydb = mongoose.connection;
console.log('ismydb');
mydb.on('error', console.error.bind(console, 'connection error:'));
mydb.once('open', function() {
// we're connected!
console.log('Connected to MongoDB');
var Schema = mongoose.Schema,
objectId = Schema.objectId;
var postSchema = mongoose.Schema({//With Mongoose, everything is derived from a Schema.
//id: objectId,//对象id
name: {type: String,default:20},
gender: {type: String,default:'male'},
// created_at: Date
}, { timestamps });
//add "speak" functionality to our documents:
postSchema.methods.speak = function(){
var greeting = this.name
? "His name is " + this.name
: "I do not have a nanme";
console.log(greeting);
}
//The next step is compiling our schema into a Model
var myModel = mongoose.model('try',postSchema);
var instance = new myModel({name:'roger',gender:'female'});
console.log(instance.name,instance.gender);
instance.save(function(err,instance){
if(err){
return console.error(err);
}
instance.speak();
});
//access all of the kitten documents through our myModel model.
myModel.find(function(err,tries){
if(err){return console.error(err)}
console.log(tries);
});
});
MORE:
ACCORDING DOCS:http://mongoosejs.com/docs/index.html
ADD 2:
It seems that when I deletes the content of the mydb.once's callback function, it still shows the same problem.
You are trying to create another connection without closing the current one. you should use
createConnection() instead of connect().
It would look like:-
db = mongoose.createConnection(url);
Some sample linls for your help,
Why am I getting error "Trying to open unclosed connection."?
Mongoose Trying to open unclosed connection
The error is implying that you have already connected once in your application. Trying to connect again will throw the exception you're seeing.
Related
I am totally absolutely novice to MongoDB and this is my first ever venture. I am still scraping around for basic ideas and procedures. Trying to build just a basic sample application with React and MongoDB as backend. I am trying to start the backend part of my project with nodemon server and getting error message on console.
The error that I am getting is -->
module.exports = mongoose.model('playerDB', playerDB);
^
ReferenceError: playerDB is not defined
at Object.<anonymous> (E:\REACT\MyProj\backend\server.js:46:45)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
[nodemon] app crashed - waiting for file changes before starting...
I do not know what I am doing honestly. Just trying random things. When I start mongo.exe and run
use playerDB
it gives me message,
switched to db playerDB
So what's the trouble? What is wrong?
My server.js code is as such -
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = 4000;
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const playerRoutes = express.Router();
let Player = require('./player.model');
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://127.0.0.1:27017/playerDB', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function () {
console.log("MongoDB database connection established successfully");
});
playerRoutes.route('/').get(function (req, res) {
Player.find(function (err, todos) {
if (err) {
console.log(err);
} else {
res.json(todos);
}
});
});
playerRoutes.route('/add').post(function (req, res) {
let player = new Player(req.body);
player.save()
.then(todo => {
res.status(200).json({ 'player': 'player added successfully' });
})
.catch(err => {
res.status(400).send('adding new player failed');
});
});
app.use('/playerDB', playerRoutes);
module.exports = mongoose.model('playerDB', playerDB);
app.listen(PORT, function () {
console.log("Server is running on Port: " + PORT);
});
So which part is wrong? Where is my mistake? When I run mongod.exe it gives me the ready message as
2019-09-15T00:41:03.305-0700 I SHARDING [LogicalSessionCacheReap] Marking collection config.transactions as collection version: <unsharded>
2019-09-15T00:41:03.306-0700 I NETWORK [initandlisten] waiting for connections on port 27017
**EDIT -> this is my player model class --> player.model.js,
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Player = new Schema({
player_name: {
type: String
},
player_description: {
type: String
},
player_position: {
type: String
},
player_age: {
type: String
},
player_club: {
type: String
},
player_: {
type: String
},
player_isactive: {
type: Boolean
},
player_completed: {
type: Boolean
}
});
Can someone direct me step by step, sequentially??
Thanks,
I have the following code in a script.js file:
var express = require('express'),
app = express(),
cons = require('consolidate'),
MongoCl = require('mongodb').MongoClient,
Server = require('mongodb').Server;
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname +'/views');
var mongoclient = new MongoCl( new Server('localhost', 27017, {'native_parser' : true}));
var db = mongoclient.db('course');
app.get('/', function (req,res) {
db.collection('hello_mongo_express').findOne({}, function (err, doc) {
res.render('hello',doc);
});
});
app.get('*', function (req,res) {
res.send('Page not found',404);
});
mongoclient.open(function (err, mongoclient) {
if(err) throw err;
var port = 8080;
app.listen(port);
console.log("Express server started on port "+port);
});
./views/hello.html looks like :
<h1>Hello, {{name}}</h1>
I have a valid collection within a db 'course'.
When I try running using node, I face the following issue:
F:\mongo_proj>node script.js
F:\mongo_proj\script.js:11
var db = mongoclient.db('course');
^
TypeError: mongoclient.db is not a function
at Object.<anonymous> (F:\mongo_proj\script.js:11:22)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
Even though, I guess all the code that creates the mongoclient, db objects, will get called only when the db connectivity is been established. So what could the issue be
edit:
I tried #jerry's suggestion:
try this.. this simple way of connection
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.close();
});
refer this link and try this
https://www.npmjs.com/package/mongodb
This issue is coming because, you are trying to use mongoclient before it opens connection. So wrap the code in open function as follow:
var db;
mongoclient.open(function (err, mongoclient) {
db = mongoclient.db('course');
if(err) throw err;
var port = 8080;
app.listen(port);
console.log("Express server started on port "+port);
});
See the link for further reference mongo connection
Also this .open() method is used in older versions. With newer version use .connect() method instead. For later versions may be refer this node driver manual
So I 100% copy pasted a code from the link below and I get the error below. I have installed all the dependencies required. I have used socket.io previously without problems, but never socket.io.users. The goal is to identify each PC as user.
var chatUsers = socketUsers.Users.of('/chat'); //
^
TypeError: Object #<Users> has no method 'of'
at Object.<anonymous> (/var/www/100moneta/components_not_larval/socket-user.js:16:35)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
My code:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var socketUsers = require('socket.io.users');
socketUsers.Session(app);//IMPORTANT
var rootIo = require('socket.io')(server); //default '/' as namespace.
var chatIo = rootIo.of('/chat');
var rootUsers = socketUsers.Users; /* default '/' as namespace. Each namespace has IT's OWN users object list,
but the Id of a user of any other namespace may has the same value if request comes from the same client-machine-user.
This makes easy to keep a kind of synchronization between all users of all different namespaces. */
var chatUsers = socketUsers.Users.of('/chat'); //
rootIo.use(socketUsers.Middleware());//IMPORTANT but no errors if you want to skip it for a io.of(namespace) that you don't want the socket.io.users' support.
chatUsers.use(socketUsers.Middleware());
chatUsers.on('connected',function(user){
console.log(user.id + ' has connected to the CHAT');
user.set('username', 'username setted by server side'); /*at the store property you can store any type of properties
and objects you want to share between your user's sockets. */
user.socket.on('any event', function(data){ //user.socket is the current socket, to get all connected sockets from this user, use: user.sockets
});
chatIo.emit('set username',user.get('username')); //or user.store.username
});
rootUsers.on('connected',function(user){
console.log('User has connected with ID: '+ user.id);
});
rootUsers.on('connection',function(user){
console.log('Socket ID: '+user.socket.id+' is user with ID: '+user.id);
});
rootUsers.on('disconnected',function(user){
console.log('User with ID: '+user.id+'is gone away :(');
});
//You can still use the io.on events, but the execution is after connected and connection of the 'users' and 'chatUsers', no matter the order.
rootIo.on('connection',function(socket){
console.log('IO DEBUG: Socket '+ socket.id+ ' is ready \n');
});
Link with the code and tutorial: https://www.npmjs.com/package/socket.io.users
I am trying to run parse server with nodejs in ibm bluemix but it is throwing an error in parse server PromiseRouter file.
PromiseRouter.js:48
throw _iteratorError;
^
ReferenceError: Symbol is not defined
How can i get this resolved
My App .js
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var app = express();
var port = process.env.PORT || 1337;
// Specify the connection string for your mongodb database
// and the location to your Parse cloud code
var api = new ParseServer({
databaseURI: 'mongodb://IBM_MONGO_DB',
cloud: './cloud/main.js', // Provide an absolute path
appId: 'MYAPPID',
masterKey: 'MYMASTER_KEY', //Add your master key here. Keep it secret!
serverURL: 'http://localhost:' + port + '/parse' // Don't forget to change to https if needed
});
app.use('/parse', api);
app.get('/', function(req, res) {
res.status(200).send('Express is running here.');
});
app.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
Response :
/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/node_modules/parse-server/lib/PromiseRouter.js:48
throw _iteratorError;
^
ReferenceError: Symbol is not defined
at PromiseRouter.merge (/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/node_modules/parse-server/lib/PromiseRouter.js:33:40)
at new ParseServer (/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/node_modules/parse-server/lib/index.js:137:10)
at Object.<anonymous> (/Applications/MAMP/htdocs/IBM_bluemix/Development/my_node_app/app.js:10:11)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
This is the function in PromiseRouter.js that is throwing an error
PromiseRouter.prototype.merge = function (router) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = router.routes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var route = _step.value;
this.routes.push(route);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
};
This is all i have
The reason why Symbol is not found is because it is an ES6 feature that is not supported in your current Node.js build. Check to make sure your Node.js runtime is at least v4 (see compatibility here).
The easy way to ensure your Node.js build on Bluemix is running at least v4.0 is to define your engine variable in your app's package.json file as such:
{ "engines" : { "node" : ">=4.0" } }
After updating your package.json file, re-push your application to Bluemix and it will build it with your defined version of Node.js
I just start use Node.JS , try to connect to MongodbLab , I follow the doc http://docs.mongolab.com/#connect
but can not insert any data in my collection "team" the error keep saying TypeError: Cannot read property 'insert' of undefined , I google for 2 hrs ,Help please.
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
var mongoose = require('mongoose');
var uri = "mongodb://awei:RRRRR#ds061365.mongolab.com:61365/aweitest";
mongoose.createConnection(uri);
// we're connected!
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
db.once('open', function() {
});
db.team.insert({ "name" : "Awei" });
error
c:\Users\awei\WebstormProjects\untitled\app.js:22
db.team.insert({ "name" : "Awei" });
^
TypeError: Cannot read property 'insert' of undefined
at Object.<anonymous> (c:\Users\awei\WebstormProjects\untitled\app.js:22:8)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:140:18)
at node.js:1001:3
Process finished with exit code 1
From what I am seeing, you need to connect with a username and password. See this:
http://docs.mongolab.com/connecting/
under "Finding your database connection info".
In addition, MongoLab offers getting-started help for Node.js here:
http://docs.mongolab.com/languages/
Once you are actually connected to the database, you should be able to insert data to the team collection.
You can access a pre-existing collection without the model using the mongoose connection's db object as follows:
var uri = "mongodb://awei:RRRRR#ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
var conn = mongoose.connection,
db = conn.db;
conn.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
conn.on('open', function() {
console.log("mongodb is connected!!");
db.collection("team", function (err, collection) {
collection.insert({ "name" : "Awei" }, function(err, result){
console.log(result);
});
});
});