node.js: Mongodb db.collection.find() not working while collection.insert works

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' } }

Answers:

Answer

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
    }
});
Answer

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();
Answer

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

Answer

you can use like that

app.get('/', (req, res) => {
  db.collection('quotes').find().toArray((err, result) => {
    console.log(result);
    })
})

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.