0

I have opened a connection to my remote mongodb ec2 instance but now am trying to retrieve data that is nested within a collection. The database has multiple collections (ie visitor, campaign, form, etc...) and has data already in it from another source. I am using node + express for the application.

1) Do I have to define a schema in my app to match the remote database or can I just query for the data and store it in an object? mongoose schema creation

2) Actually retrieving the values within the visitor collection, can I just use dot notation to query within the visitor collection for visitor_id using:

db.find(visitor.visitor_id)  

Here is the database connection code I am using if that helps

var uri = 'mongodb://xx.xxx.xx.x'
var mongoOptions = { db: { safe: true } };
  db = mongoose.createConnection(uri, mongoOptions, function (err, res) {
if (err) {
    console.log('ERROR connecting to: remote' + uri + '. ' + err);
} else {
    console.log('Successfully connected to: remote' + uri);
   }
});
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

0
  1. If you're using mongoose, then yes, you need to define a schema in your app to match the database.
  2. That notation won't work. If I understand the specific query you're trying to make (to fetch the document matching a visitor_id) then you'll need something roughly like this:

    // Assuming you already have mongoose connected to the database elsewhere
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var visitorSchema = new Schema({
        visitor_id: Number,
        etc: etc // the rest of your schema
    });
    var Visitor = mongoose.model('Visitor', visitorSchema);
    
    Visitor.findOne({ visitor_id: the_id_you_want_to_query }, function (err, doc) {
        // doc contains the visitor document, if found
    });
    

I suggest you familiarize yourself with queries with MongoDB and mongoose in particular—the docs aren't super easy to understand but cover most of the main cases.

Jorge Aranda
  • 2,050
  • 2
  • 20
  • 29
  • Thanks Jorge, that helped clarify some things. How would it change if I wanted to query the whole db and only return those that had a a visit_id != null(most are null, while others have a unique id). – Nick Remlinger Oct 09 '14 at 18:32
  • Querying for non-nulls is a bit messy. One way to do it is with the `$type` operator--this page should help: http://docs.mongodb.org/manual/faq/developers/#faq-developers-query-for-nulls – Jorge Aranda Oct 10 '14 at 04:24