Pregunta

I am using mongodb in a nodejs app I am currently writing.

Upon running an insert in my code, I get the following error back: ReferenceError: collection is not defined at /home/safeuser/lunchand/routes/talktomongo.js:17:7

As far as I can tell from docs, simply running insert in a collection should create it! If I open mongo manually in my terminal and run show dbs I also never see lunchand in the list of dbs, just local and admin.

Here's the code I'm using. Line 17 is where the collection.insert is. Any help would be greatly appreciated.

//Declarations
var mongo = require('mongodb'),
    Server = mongo.Server,
    Db = mongo.Db,
    server = new Server('localhost', 27017, {auto_reconnect: true}),
    db = new Db('lunchand', server);

//Open database
db.open(function(_err, _db) {
    if(!_err) {
        console.log("Connected to lunchand DB");
        db.collection('lunchers', {strict: true}, function(_err, _collection) {
            if(_err) {
                console.log("Lunchers collection doesn't exist! Let's fix that!");
                var testLuncher = {username:"username",pwd:"password",officeLocation:"Office Location",teams:"teams",shark: true};
                db.collection('lunchers', function(_err, _collection) {
                    collection.insert(testLuncher, {safe:true}, function(_err, _result) {});
                });
            } else {
                console.log("Oh it exists");
            }
        });
    } else {
        console.log("Error Connecting to Station DB: " + _err);
    }
});
¿Fue útil?

Solución

try to add the name of the collection to the object something like this:

db.collection("lunchers").insert(testLuncher,function(err, element){
                    console.log("element inserted");  
                  });

probably your code should look like:

var mongo = require('mongodb'),
    Server = mongo.Server,
    Db = mongo.Db,
    server = new Server('localhost', 27017, {auto_reconnect: true}),
    db = new Db('lunchand', server);

//Open database
db.open(function(_err, _db) {
    if(!_err) {
        db.collection('lunchers', {strict: true}, function(_err, _collection) {
            if(_err) {
               var testLuncher = {username:"username",pwd:"password",officeLocation:"Office Location",teams:"teams",shark: true};
                db.collection("lunchers").insert(testLuncher,function(err, element){
                console.log("element inserted");  
              });


            } else {
                console.log("Oh it exists");
            }
        });
    } else {
        console.log("Error Connecting to Station DB: " + _err);
    }
});

Otros consejos

I would guess that line 17 should actually be either db.collection.insert(... or _collection.insert(...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top