Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

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

Solution 3:

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

Solution 4:

you can use like that

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

Post a Comment for "Node.js: Mongodb Db.collection.find() Not Working While Collection.insert Works"