简体   繁体   中英

Mongoose Schema for remote MongoDb

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);
   }
});
  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.

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