简体   繁体   中英

Typerror: mongo module's find method is undefined

I'm new to NodeJS and I am expirimenting with MongoDB. However I have an error which is in my eyes pretty weird: TypeError: Cannot call method 'find' of undefined. I'm trying to use the ' find ' method from the node mongo module, collection.find({id: "1"}, callback) but all I get is that error. However, the strange thing is that an insert does work. What is the problem?

db.collection('users', function(error, collection)
{
    console.log('Collection:'); 
    // ================ THIS WORKS =================
    // insert : 

    // collection.insert({

    //  id: "1", 
    //  name: "Marciano", 
    //  email: "email@email.nl", 

    // }, function()
    // {
    //  console.log('inserted!');
    // }); 

    // collection.insert({

    //  id: "2", 
    //  name: "Edward Elric", 
    //  email: "edward_elric@live.nl", 

    // }, function()
    // {
    //  console.log('inserted!')
    // }); 
    // ======= THIS DOESNT WORK ========
    // select: 
    // specify an object with a key for a 'where' clause
    collection.find({'id': '1'}, function(error, cursor)
    {
            //cursor : iterateing over results

            cursor(function(error, user)
            {
                console.log("found:" + user);
            })

    })



}); 

That is not how you iterate a Cursor object returned from .find() . Use the .each() or .toArray() methods in order to deal with results instead.

collection.find({ "id": 1 }).toArray(function(err,data) {
    // data is an array of objects from the collection
});

It is caused beucase you insert record to database and dont wait for callback. If you want to do this sequentualy, I suggest you to use async and method waterfall. But anyway it would be better to use Mongoose instead that you are using now. and write something like this

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/collection');

var user = new User({ name: 'John' });
user.save(getInsertedUsers);

var getInsertedUsers = function(){
    User.find({ name: "John" }, echoUsers);  //if you want to get just users named john or
    User.find({}, echoUsers);
}
var echoUsers = function(users)
{
    console.log(users);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM