如何使用node.js从mongodb获取数据

时间:2017-07-24 10:43:32

标签: javascript node.js mongodb mongoose

我尝试在node.js中使用此代码从mongoDB中获取数据,但它甚至没有显示任何错误或结果。我已经测试了DB,有很多可用的数据,如[数据库输出]

    {
    "_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. 模态/ 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);
    

2 个答案:

答案 0 :(得分:0)

您尚未连接到MongoDB服务器(使用mongoose)。

选择使用mongoose或mongodb库,而不是两者。仔细检查文档。

答案 1 :(得分:0)

你加载mongo和mongoose但你用mongo连接,你的文件用mongoose存储。所以只需删除mongo并与mongoose连接

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