Reputation: 73
I am trying to incorporate mongoDB into my application, however when I try to add to a collection I get the error 'cannot read property of 'insert' undefined when trying to start the server with nodeJS.
I appreciate that this has been asked before, however when I have tried to rectify the error as per another question asked on here by writing the following code, however I get var
is not defined;
var accountCollection = var mongodb = mongodb.collection('account');
accountCollection.insert({username:"wendy3", password:"lilac3"});
The relevant code for my server is below, I have looked at many guides online and nothing seems to solve my problem, so any help would be appreciated.
//create server, listening on port 3000
//when there is a request to port 3000 the server is notified
//depending on the request a specific action will be carried out
var mongodb = require("mongodb");
//create connection to MongoDB
var db = mongodb('localhost:27017/Game', ['account', 'progress']);
//insert into collection
db.account.insert({username:"wendy3", password:"lilac3"});
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var colors = require('colors/safe');
Upvotes: 2
Views: 72
Reputation: 73
Thank you - I think I understand now ( I am new to MongoDB so please forgive me)
I now have the following code; however I am receiving error invalid schema, expected mongodb.
Have I maybe put MongoClient
in place of mongodb
somewhere? So I can see that it is trying to connect, however the callback is returning an error.
Code:
var MongoClient = require('mongodb').MongoClient;
//connection url
var url = ('localhost:27017/Game', 'account', 'progress');
//use connect method to connect to server
MongoClient.connect(url, function(err, db){
if (err) return console.log('Error: ' + err);
console.log('mongodb is connected to the server');
});
Upvotes: 0
Reputation: 35491
Connection to a database is an asynchronous operation but you're trying to access it as if it was synchronous.
If you look at the examples for the package you're using, it shows that you must you use a callback function which gets called once the connection response is received:
var MongoClient = require('mongodb').MongoClient;
// Connection URL
var url = 'localhost:27017/Game';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
if (err) return console.log('Error: ' + err);
console.log("Connected correctly to server");
});
Upvotes: 2