7

I'm using node.js/express and I have a Mongodb to store some sets of data. On a webpage the user can enter, edit and delete data (which all works fine). For example, to add data I have the following code:

 router.post('/addset', function(req,res) {
    var db = req.db;
    var collection = db.get('paramlist');
    collection.insert(req.body, function(err, result){
        res.send(
            (err === null) ? { msg: '' } : { msg: err }
        );
    });
});

In my app.js file I include the lines

// Database
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/paramSet1');

as well as

app.use(function(req,res,next){
    req.db = db;
    next();
});

to make the database accessible in the rest of the code (following this tutorial: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ , I'm a beginner with these things).

So all this works fine. My problem is the following: I would like to add a test if a dataset with the same name is already in the database and give a message to the user. Following this answer How to query MongoDB to test if an item exists? I tried using collection.find.limit(1).size() but I get the error

undefined is not a function

I tried the following things. In the cost above (router.post) I tried adding after the line var collection...

var findValue = collection.find({name:req.body.name});

If i then do console.log(findValue), I get a huge output JSON. I then tried console.log(findValue.next()) but I get the same error (undefined is not a function). I also tried

collection.find({name:req.body.name}).limit(1)

as well as

collection.find({name:req.body.name}).limit(1).size()

but also get this error. So in summary, collection.insert, collection.update and collection.remove all work, but find() does not. On the other hand, when I enter the mongo shell, the command works fine.

I would be grateful for any hints and ideas.

Edit: The output to console.log(findValue) is:

    { col:
   { manager:
      { driver: [Object],
        helper: [Object],
        collections: [Object],
        options: [Object],
        _events: {} },
     driver:
      { _construct_args: [],
        _native: [Object],
        _emitter: [Object],
        _state: 2,
        _connect_args: [Object] },
     helper: { toObjectID: [Function], isObjectID: [Function], id: [Object] },
     name: 'paramlist',
     col:
      { _construct_args: [],
        _native: [Object],
        _emitter: [Object],
        _state: 2,
        _skin_db: [Object],
        _collection_args: [Object],
        id: [Object],
        emitter: [Object] },
     options: {} },
  type: 'find',
  opts: { fields: {}, safe: true },
  domain: null,
  _events: { error: [Function], success: [Function] },
  _maxListeners: undefined,
  emitted: {},
  ended: false,
  success: [Function],
  error: [Function],
  complete: [Function],
  resolve: [Function],
  fulfill: [Function],
  reject: [Function],
  query: { name: 'TestSet1' } }
Community
  • 1
  • 1
Tokeloshe
  • 73
  • 1
  • 1
  • 6

5 Answers5

4

find returns a cursor, not the matching documents themselves. But a better fit for your case would be to use findOne:

collection.findOne({name:req.body.name}, function(err, doc) {
    if (doc) {
        // A doc with the same name already exists
    }
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
1

If you're using the method on that website http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ you have to change your code

collection.find({name:req.body.name}).limit(1)

and use it like this

collection.find({name:req.body.name},{limit:1})

and if you want to add more options do like this

collection.find({name:req.body.name},{limit:1,project:{a:1},skip:1,max:10,maxScan:10,maxTimeMS:1000,min:100})

You can find everything here http://mongodb.github.io/node-mongodb-native/2.0/api/Cursor.html

Nick
  • 138,499
  • 22
  • 57
  • 95
IXOVER
  • 531
  • 4
  • 4
1

you can use like that

app.get('/', (req, res) => {
  db.collection('quotes').find().toArray((err, result) => {
    console.log(result);
    })
})
Khalid Bin Huda
  • 1,583
  • 17
  • 16
0

The first thing that looks wrong is your syntax is incorrect for find. You need to call it as a function. Try:

collection.find({name:req.body.name}).limit(1).size();
tom
  • 1,331
  • 1
  • 15
  • 28
  • Thanks for your answer. That is in fact what I had tried and what gave me the error, but I mistyped it when I posed the question. Very sorry about that. I have edited the question now. – Tokeloshe Jun 27 '15 at 12:55
  • You say you get huge JSON output. Does it contain the expected data? If it's unreadable, try a JSON formatter [like this one](http://www.freeformatter.com/json-formatter.html). – tom Jun 27 '15 at 13:00
  • I have added the output in the question. I don't think it contains the expected data. – Tokeloshe Jun 27 '15 at 13:04
  • From that output, I don't see a "limit" function returned, but I do see success, error, complete, etc. Perhaps the version of Mongo you have installed is different from the Mongo version your application is using? Try calling one of the methods returned from the find() – tom Jun 27 '15 at 13:15
0

Probably you might have missed to connect a Database.

Try adding below code before executing

mongodb.connect(dbURI).then((result)=>console.log('connected to DB')).catch((err)=>console.log('connected to DB'));
Pavan Pyati
  • 950
  • 2
  • 13
  • 18