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);
});
});
});
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 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.
I am very close to an express app working in a sandbox environment on Heroku with a MongoDB addon..
I am still seeing a ReferenceError in the log, which seems to be the reason for the app crashing.
The first error was regarding this configuration:
//MongoDB
var mongodb = require('mongodb');
var db;
var MONGODB_URI = process.env.MONGOLAB_URI;
var PORT = process.env.PORT;
mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
if(err) throw err;
db = database;
app.listen(PORT);
console.log('Listening on port ' + PORT);
});
var testColl = db.collection('test');
That led to the log reading a TypeError, probably because db was defined locally..
app[web.1]: var testColl = db.collection('test');
app[web.1]: TypeError: Cannot call method 'collection' of undefined
And the recent error was a ReferenceError:
app[web.1]: var db = database;
app[web.1]: ReferenceError: database is not defined
Probably because database is defined globally, but not referenced within the context of the connection..
//MongoDB
var MongoClient = require('mongodb').MongoClient,
var Server = require('mongodb').Server;
var mongoUri = process.env.MONGOLAB_URI;
var port = process.env.PORT;
var db = database;
var mongoclient = new MongoClient(new Server(mongoUri,
{ 'native_parser' : true }));
var testColl = db.collection('test');
mongoclient.open(function (err, mongoclient) {
if (err) throw err
app.listen(port);
console.log("Express server started on port " + port);
});
How can I reformat the code to launch this app on Heroku?
Your first example looks close to working, but there's one thing wrong. mongodb.connect is an asynchronous call, which means it returns right away. That's why it has the callback parameter. Because the code runs so fast, it doesn't have time to actually connect to the database before you try to use the db object, which is what causes your crash in the first set of code.
If you move your database call inside the callback, it should work.
Edit: This is in reply to your comment, but I can't include much code in another comment, so you get an edit.
It really depends on your use case, but I realize that's not very helpful. So here's one way you could do it:
module.exports = function() {
return db;
};
By doing so, you would be able to require it from another file, and use it as such:
var http = require('http');
var db = require('./db.js');
http.createServer(function(req, res) {
db().collection('test', function(err, collection) {
console.log(err, collection);
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('We got it! Unless there is an error...\n');
});
}).listen(8080);
There's definitely ways to improve upon that, but it should get you started.