2

I am working on trying to connect a Node/Express server to an existing MongoDB Database/Collection. I have already successfully connected to the database. However, I am having a tremendously difficult time setting up my models/schema to query.

The MongoDB is MongoDB Atlas and has one collection with over 800,000 documents. The name of the single collection is "delitosCollection".

I have tried the following to with no success:

var CrimeData = mongoose.model('DelitosCollection', new Schema({}),'delitosCollection');


mongoose.connection.on('open', function(ref){
    console.log("connected to the mongo server");

   CrimeData.find({}, (err,results) => {
       if(err){
           console.log("ERROR")
           throw err
       }
       console.log("results: ", results.length)
   } )
});

I know the connection is working as I am receiving the console.log with no errors. However, results.length is returning 0 when it should be over 800,000. Have spent way too many hours on this.

FDRH
  • 209
  • 3
  • 11
  • Possible duplicate of https://stackoverflow.com/questions/5794834/how-to-access-a-preexisting-collection-with-mongoose – wlh Jan 04 '19 at 22:52

3 Answers3

2

Create an empty schema for each collection you want to use and then create a model to be used in your project the model take 3 parameter 1)name of the model 2)schema name 3)collection name ( from mongodb atlas)

like that

const mongoose = require('mongoose');
mongoose.connect('mongodb uri')
const userSchema = new mongoose.Schema({});
const User = mongoose.model('User', userSchema, 'user');

then you can use the model normally

User.find({})
M.Amer
  • 658
  • 6
  • 13
0

connection to mongo db

// Connect to mongoDB
mongoose.connect('mongodb://localhost/[yourDbName]',{useNewUrlParser:true})
    .then(function(){
        console.log('mongoDB connected');
    })
    .catch(function(){
        console.log('Error :');
    }) 

after that you will have to create your schema and then only you can query the database

create your schema like this

// Crimes Schema 
const CrimeDetailsSchema= new Schema({
    first_name: {
        type: String,
        required: true
    },
    last_name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    }

});

const Profile = module.exports = mongoose.model('delitosCollection', CrimeDetailsSchema, 'delitosCollection');

after that create your queries

you can get an idea about that in mongoose documentation here

ALPHA
  • 1,135
  • 1
  • 8
  • 18
0

You can refer to the answer given below, just pass an empty object in schema like db.model('users', new Schema({}))