简体   繁体   中英

How to fetch data from mongodb using node.js

I'm try to fetch data from mongoDB using this code in node.js, but It's not working even not show any error or result. I have already test DB, there is lots for data available like [Database output]

    {
    "_id" : ObjectId("597321311e13c57335727a6d"),
    "name" : "Amanda",
    "publisher" : "MTV india"
    }
    {
    "_id" : ObjectId("5973220b1e13c57335727a6e"),
    "name" : "Deepka",
    "publisher" : "MTV"
    }
    {
    "_id" : ObjectId("597322141e13c57335727a6f"),
    "name" : "sunil",
    "publisher" : "MTV india"
    }
  1. app.js

     var express = require('express'); var app = express(); var MongoClient = require('mongodb').MongoClient; var mongoose = require('mongoose'); var booksDetail = require('./modal/book'); var url = "mongodb://localhost:27017/example"; // Connect to the db MongoClient.connect(url); app.get('/api/books', function(req,res) { res.send("on book page"); booksDetail.find({}) .exec(function(err, books) { console.log("--working--"); if(err) { res.send('error occured') res.send('error occured') } else { console.log(books); res.json(books); } }); }); app.get('/api/school', function(req,res){ res.send('hello this is school page'); }); app.listen(7900); console.log('server is runing 7900') 
  2. modal/book.js

     var mongoose = require('mongoose'); var Schema = mongoose.Schema; var bookSchema = new Schema({ name: { type: String, requierd: true }, publisher : { type: String, requierd: true } }) module.exports = mongoose.model('booksDetail', bookSchema); 

You haven't connected to your MongoDB server (using mongoose) yet.

Choose to use either mongoose or mongodb library, not both. Check it docs carefully.

you load mongo and mongoose but you connect using mongo and your document is stored with mongoose. So just remove mongo and connect with mongoose

mongoose.connect('mongodb://localhost:27017/example');
var db = mongoose.connection;  
db.once('open', function() {
    console.log('OPEN');
});

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