I need to develop a Meteor app using external MongoDB, but I'm not sure how to connect and fetch external Mongo data using Meteor.
The following is what I've tried.
Fetch external MongoDB data in the shell (success)
I can connect into external MongoDB under Terminal (use database sm_app):
$ mongo <USER>:<PASSWORD>@<SERVER>:<PORT>/sm_app
and fetch the only one data:
> db.servertop10.findOne()
It shows:
{
"_id": ObjectId("......")
"list": [
...
]
}
Fetch external MongoDB data in Meteor (failed)
Now I try running Meteor with external MongoDB on my Mac:
MONGO_URL=mongodb://<USER>:<PASSWORD>@<SERVER>:<PORT>/sm_app meteor run
then try to fetch data in Meteor.js:
import { Mongo } from 'meteor/mongo';
const ServerMonitor = new Mongo.Collection('servertop10');
console.log('findOne:', ServerMonitor.findOne());
but it shows:
findOne: undefined
Questions
- How can I fetch the data under Meteor.js?
- Is it possible using other databases in Meteor.js with the same external MongoDB? How to do this?
Edit
Previously, I only tried fetch data on the front end. Now I try logging the results on both server side and client side.
// Import this file on the main.js files of both server and client
import { Mongo } from 'meteor/mongo';
const ServerMonitor = new Mongo.Collection('servertop10');
Meteor.startup(() => {
console.log('MONGO_URL:', process.env.MONGO_URL);
console.log('findOne:', ServerMonitor.findOne());
}
The server side shows:
> MONGO_URL: mongodb://<USER>:<PASSWORD>@<SERVER>:<PORT>/sm_app
> findOne: {
"_id": ObjectId("......")
"list": [
...
]
}
but the client side shows:
> MONGO_URL: undefined
> findOne: undefined
I still failed to fetch the data in the render() of a React component:
render() {
// still print `undefined`
console.log('findOne:', ServerMonitor.findOne());
return (<h1>Hello</h1>);
}
but I can fetch the data on the console of the browser (with autopublish):
> ServerMonitor.findOne()
Object {_id: ..., ...}
I don't know why I can't fetch the data on the client side.
Meteor.startup(() => console.log(process.env.MONGO_URL))printsundefinedprocess.env.MONGO_URLon the server side and fetch the data, and it worked well. When I tried to fetch data on the client side using the same collection code, I got nothing. I have no idea about this. Please see the new edit on the post.undefinedon client console because at that time server has not finished sending data yet