0

I try connect my MongoDB database. I use Node.js with Express.js.
I try create schema and parse object into JSON, but doesn't work. This is index.js:

var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');
var mongoose = require('mongoose');
var util = require('util');
var serwer = new mongodb.Server('127.0.0.1', 27017);

var mesons;

new mongodb.Db('test',serwer).open(
        function(err,client){
            if (err) throw err;
            console.log('Polaczyles sie baza Mongo');
            mesons = new mongodb.Collection(client,'mesons'); 
});

var mesonsSchema = new mongoose.Schema({
    Name: String,
    Mass: String,
    Charge: String, 
    LifeTime: String,
    AntiParticle: String,
    Type: String,
    Width: String,
    IJPC: String,
    MagneticMoment: String

});

var mesonsModel = mongoose.model('mesons', mesonsSchema );

/* GET home page. */
router.get('/', function(req, res, next) {
     return mesonsModel.find(function( err, mesons) {
         if( !err ) {
             return res.json( mesons );
         } else {
             console.log( err );
             return res.json( { error: 'No data returned'} );
         }
    });
});

module.exports = router;

When I connect localhost there is no results, no errors and loading and loading...

1 Answer 1

1

You need to make sure you start a mongoose connection to the database. It looks like the connection is not made so the mesonsModel.find call is just hanging. Instead of connecting directly with the mongodb drive you can connect via mongoose:

mongoose.connect('mongodb://127.0.0.1:27017/test');

You can wait to see if the connection is successful by listening for the open event:

mongoose.connection.once('open', function (callback) {
  // now you can query the database
});

You should remove the whole mongodb.Db() call

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.