I have 2 webservers that I have created on ports 3000 and 4000.
One of the webservers created a database and has 3 collections..
show dbs
local 0.000GB
sensor_db 0.000GB
use sensor_db
switched to db sensor_db
show collections
sensors
templategroups
templates
Can the 2nd server access this Database created ? if yes, I am not able to access the collections ..Is there any syntax to it?
1st server:
var express = require('express');
var app= express();
var path = require('path');
var bodyParser= require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sensor_db');
var Schema = mongoose.Schema;
var sensorSchema = new Schema({
value:{ type:Number, default:0},
format:{type:String, default:"default"},
id:{type:Number,required:true,unique:true},
description:{type:String},
type:{type:String},
groupId:{type:Number},
users:{type:Array,default:[]},
admin:{type:String,default:'Undefined'},
status:{type:String,default:'Undefined'},
owner:{type:String,default:'Undefined'},
templateId:{type:Number}
});
var Sensor = mongoose.model('Sensor',sensorSchema);
app.get('/sensorlist',function(req,res) {
console.log("I recieved a GET /sensorlist request");
Sensor.find(function(err,data){
if (err) return console.error(err);
console.log(data);
res.json(data)
});
});
app.post('/check/health',function(req,res){
socket.emit('data', 'I need your health status', function ack(data) {
console.log('data emit was acknowledged by Monitoring Server:', data);
return res.json(data);
});
});
2nd Server:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var express = require('express');
io.on('connection', function(socket){
console.log('connection received from Provisioning');
// To get messages from Provisioning server
socket.on('data', function(data, ack) {
console.log('Message from provision is : ' + ': ' + data);
ack('here is your data - 1111');
console.log("Trying to access the Sensor_DB Database");
Sensor.find(function(err,data){
if(err) return console.error(err);
console.log(data);
//res.json(data);
});
});
});
server.listen(4000, function(){
console.log('socket.io server listening on *:4000');
});
I get error - Sensor is not defined
Much Thanks
Jessi
I tried to dispay the collections once its connected to the DB but get this error message : Cannot read property 'hasListCollectionsCommand' of null
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/sensor_db') ;
console.log("successfully connected to the database");
//mongoose.connection.db
mongoose.connection.db.listCollections().toArray(function(err, names) {
if (err) {
console.log(err);
}
else {
names.forEach(function(e,i,a) {
mongoose.connection.db.dropCollection(e.name);
console.log("--->>", e.name);
});
}
});
Two Different servers cannot share the same instance of the sensor object.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sensor_db');
var Schema = mongoose.Schema;
var sensorSchema = new Schema({
value:{ type:Number, default:0},
format:{type:String, default:"default"},
id:{type:Number,required:true,unique:true},
description:{type:String},
type:{type:String},
groupId:{type:Number},
users:{type:Array,default:[]},
admin:{type:String,default:'Undefined'},
status:{type:String,default:'Undefined'},
owner:{type:String,default:'Undefined'},
templateId:{type:Number}
});
var Sensor = mongoose.model('Sensor',sensorSchema);
This code declaring the schema for one server not for the second . so you have to declare the instance in the second server also.
Issue not with the mongo data base issue is the sensor instance that is not have any declaration in second server.
Related
I am making a simple test for RESTApi using Node.js, mongodb and express from this article:
MERN Part I: Building RESTful APIs with Node.js and Express
but there is an error somewhere in code i can't locate. The author of article used babel but due to some other error i avoided it. Given below are code files:
App.js
var routes= require('./src/routes/userRoutes').routes
var express= require("express")
var mongoose=require('mongoose')
var bodyParser=require('body-parser')
const app = express();
const PORT=4001
// SET INDEX PAGE
app.get('/',function(req,res){
res.send(`Node and express server running on PORT ${PORT}`);
});
// START SERVER
app.listen(PORT,function(){
console.log(`Your server is running on PORT ${PORT}`);
});
// ESTABLISH ROUTES
routes(app)
// Join Database to API
mongoose.Promise= global.Promise;
mongoose.connect('mongodb://localhost/userdb', {
useNewUrlParser:true,
useUnifiedTopology:true
})
// body-parser setup
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
userModel.js : I have commented out the "required" to avoid the Validation Error and see what document is being saved in the collection.
var mongoose = require('mongoose')
const Schema = mongoose.Schema;
const UserSchema = new Schema({
userName:{
type:String,
//required:"Enter your name",
},
UserID:{
type:Number,
//required:"Enter User ID:",
},
password:{
type:String,
// reequired:"Enter your password?",
}
});
module.exports={UserSchema}
userController.js:
var mongoose=require('mongoose')
var UserSchema = require("../models/userModel").UserSchema;
const UserModel= mongoose.model("Users",UserSchema)
const addNewUser = (req,res) => {
let newUser= new UserModel(req.body);
newUser.save((err,user) => {
if(err) res.send(err)
else res.json(user)
})
}
module.exports={addNewUser}
userRoute.js:
var addNewUser = require('../controllers/userController').addNewUser;
const routes = (app) => {
// create routes for login/signup/view
app.route('/users')
.get((req,res)=> res.send("Get request successful"))
app.route('/users/:userID')
.put((req,res)=>res.send(`Put Request succesful for ${req.params.donationID}`))
.delete((req,res)=>res.send("delete Request successful"))
.post(addNewUser);
app.route('/done')
.get((req,res)=>{
res.send("Goodbye");
process.exit(0);
});
}
module.exports={routes};
Response recieved when POST request with URI:localhost:4001/users/1?userName=Adnan&UserID=123&password=0000
{
"_id": "5fd0b07b12615110d420a91b",
"__v": 0
}
Expected Output: User Object in JSON
I am trying to connect my local database, which is MongoDB with my website using Mongoose, but I am receiving Error 404. What I have to do in this situation?
--the next file is controller for my model
var mongoose = require('mongoose');
var db = 'mongodb://localhost/employeers';
var Emp = require('../models/employeers');
mongoose.connect(db);
module.exports.allEmployeers=function(req,res){
console.log('getting information about everyone employeer');
Emp.find({})
.exec(function(err,employeers){
if(err){
res.send("Error has occured");
}
else{
console.log(employeers);
res.json(employeers);
}
})
};
--my route file
var ctrlEmployeers = require('../controllers/employeers');
router.get('/employeers', ctrlEmployeers.allEmployeers);
I expect when I enter localhost:3000/employeers in the browser, every employeer of my local database to be exported in JSON format. Instead of that I receive a 404 error: Page is not found.
Try this
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/employeers', { useNewUrlParser: true });
var Emp = require('../models/employeers');
module.exports.allEmployeers=function(req,res){
console.log('getting information about everyone employeer');
Emp.find({})
.exec(function(err,employeers){
if(err){
res.send("Error has occured");
}
else{
console.log(employeers);
res.json(employeers);
}
})
};
const functions = require('firebase-functions');
var nodemailer = require('nodemailer');
var transporter=nodemailer.createTransport('smtps://username#gmail.com:password#smtp.gmail.com');
exports.sendMail=functions.https.onRequest((req,res)=>{
var mailOptions={
to: 'sender#gmail.com',
subject: 'Test Mail',
html: 'Testing with Node.js'
}
transporter.sendMail(mailOptions,function(err,response){
if(err)
{
res.send('Mail not sent');
console.log(err);
}
else{
res.send('Mail sent');
}
});
});
I want to send email to various persons over time. I want to change the to: address in this code dynamically. So how to get a particular(sendermailid) variable from another javascript file and send to that person. My folders are located as below the picture.
How to get the variable from assmt.js to index.js(cloud function js).
You need to set up an express server who is listening our other JS aplication like this :
var express = require('express');
var app = express();
Now you can listen from another app on specified port :
var port = process.env.PORT || 8080;
app.listen(port);
console.log("App listening on port " + port);
Finally you have to intercept http post request to send your mail and get user info from the request :
app.post('/api/sendmail', function(req, res) {
var mail = {
from: req.body.user.emailFrom,
to: req.body.user.emailTo,
subject: "your subject",
html: "<p>email body</p>"
}
transporter.sendMail(mail, function(error, response){
if(error){
console.log("Error!");
console.log(error);
res.send(JSON.stringify(error));
}else{
res.send(JSON.stringify(response));
console.log("Success!")
transporter.close();
}
}
Your server is now ready you can start it with :
node serverName.js
And in your other js file ( assmt.js ) you send the http request with parameter :
send(user : User) {
let body = {user};
this.httpClient.post('http://localhost:8080/api/sendconge', body)
.subscribe(function(data) {
console.log(data);
});
}
I'm building an app using node-webkit, based on expressjs and mongoose. I'm new to basically all of this.
I've got a mongoDb hosted online and i'm try to use it in my app, but i'm missing something
I created in model folder db.js, where i connect with the db
var mongoose = require('mongoose');
mongoose.connect('mongodb://user:password#ds012345.mlab.com:port/mydb') //this isn't the real link
then my model, clients.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var clientSchema = new Schema ({
name: String,
//other fields
});
var client = mongoose.model('client', clientSchema);
module.exports = client;
Then, in my app.js
var db = require('./model/db')
I'm also using routes, so in my index.js i got
var client = require('../model/clients')
But i cannot use any function (save, find, ecc.), i can just create models.
I think I'm not connecting in the right way all the modules, i was previously using diskdb and i connected to it in my index.js, but i tried in the same way and it doesn't work anyway.
Also, when i build the app, my mongoose connection status is 2.
Here are a few things:
what is ecc? you should connect to something like this: mongoose.connect('mongodb://localhost:27017/test');
27017 is the default port for MongoDB and test is the name of your database. Also make sure you start mongo server with mongod then run mongo console mongo.
Your field should specify type of the data:
var clientSchema = new Schema ({
name: String,
age: Number
});
So you want to save the document into database:
var client = mongoose.model('client', clientSchema);
var data = {
nome: 'something'
};
var user = new client(data);
user.save(function(err) {
if(err) console.log(err);
});
In your route, you can do something like this to query back and send data back to the req:
var express = require('express');
var router = express.Router();
var clientSchema = require('../models/clientSchema');
router.get('/', function(req, res, next) {
UserSchema.find({} , function(err, data) {
if (err) console.log(err);
res.render('index', {
data: data
});
});
});
module.exports = router;
Hope this help!
First question here, so be kind ;)
I am configuring a Node.js server to connect to a MongoDB database in Modulus.io node.js hosting (really good stuff, worth checking it out), but I can't seem to properly stablish connection. Per the getting-started guide I get a connection uri in the format:
mongodb://user:pass#mongo.onmodulus.net:27017/3xam913
But that doesn't seem to work with the structure of the code I was trying to port to the server (had it running locally) because of the Server class argument structure with only host and port to define...
This is the code I am trying to adapt to the connection:
// server setup
var mongo = require('mongodb'),
mdbServer = mongo.Server,
mdbDb = mongo.Db,
mdbObjectID = mongo.ObjectID;
// open a connection to the mongoDB server
var mdbserver = new mdbServer('localhost', 27017, {auto_reconnect: true});
// request or create a database called "spots03"
var db = new mdbDb('spots03', mdbserver, {safe: true});
// global var that will hold the spots collection
var spotsCol = null;
// open the database
db.open(function(err, db) {
if(!err) {
// if all cool
console.log("Database connection successful");
// open (get/create) a collection named spotsCollection, and if 200,
// point it to the global spotsCol
db.createCollection(
'spotsCollection',
{safe: false}, // if col exists, get the existing one
function(err, collection) {spotsCol = collection;}
);
}
});
Any help would be much appreciated, thanks!
Looks like a couple of things:
The connection URL should be mongo.onmodulus.net
var mdbserver = new mdbServer('mongo.onmodulus.net', 27017, {auto_reconnect: true});
rounce is correct, the database name is auto-generated by Modulus.
var db = new mdbDb('3xam913', mdbserver, {safe: true});
Modulus databases will need authentication. Before you call createCollection, you'll have to call auth and pass it the user credentials that are setup on the project dashboard.
I'm a Modulus developer, and I know the DB name thing is not ideal.
Edit: here's full source for a working example. It records every HTTP request and then sends all requests back to the user.
var express = require('express'),
mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db;
var app = express();
var server = new Server('mongo.onmodulus.net', 27017, { auto_reconnect: true });
var client = new Db('piri3niR', server, { w: 0 });
client.open(function(err, result) {
client.authenticate('MyUser', 'MyPass', function(err, result) {
if(!err) {
console.log('Mongo Authenticated. Starting Server on port ' + (process.env.PORT || 8080));
app.listen(process.env.PORT || 8080);
}
else {
console.log(err);
}
});
});
app.get('/*', function(req, res) {
client.collection('hits', function(err, collection) {
collection.save({ hit: req.url });
// Wait a second then print all hits.
setTimeout(function() {
collection.find(function(err, cursor) {
cursor.toArray(function(err, results) {
res.send(results);
});
});
}, 1000)
});
});
Wrong database name perhaps?
From the MongoDB docs on the subject '3xam913' is your database name, not 'spots03'.
var db = new mdbDb('3xam913', mdbserver, {safe: true});