How to fetch data from mongodb using node.js - javascript

I'm try to fetch data from mongoDB using this code in node.js, but It's not working even not show any error or result. I have already test DB, there is lots for data available like [Database output]
{
"_id" : ObjectId("597321311e13c57335727a6d"),
"name" : "Amanda",
"publisher" : "MTV india"
}
{
"_id" : ObjectId("5973220b1e13c57335727a6e"),
"name" : "Deepka",
"publisher" : "MTV"
}
{
"_id" : ObjectId("597322141e13c57335727a6f"),
"name" : "sunil",
"publisher" : "MTV india"
}
app.js
var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var mongoose = require('mongoose');
var booksDetail = require('./modal/book');
var url = "mongodb://localhost:27017/example";
// Connect to the db
MongoClient.connect(url);
app.get('/api/books', function(req,res) {
res.send("on book page");
booksDetail.find({})
.exec(function(err, books) {
console.log("--working--");
if(err) {
res.send('error occured')
res.send('error occured')
} else {
console.log(books);
res.json(books);
}
});
});
app.get('/api/school', function(req,res){
res.send('hello this is school page');
});
app.listen(7900);
console.log('server is runing 7900')
modal/book.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bookSchema = new Schema({
name: {
type: String,
requierd: true
},
publisher : {
type: String,
requierd: true
}
})
module.exports = mongoose.model('booksDetail', bookSchema);

You haven't connected to your MongoDB server (using mongoose) yet.
Choose to use either mongoose or mongodb library, not both. Check it docs carefully.

you load mongo and mongoose but you connect using mongo and your document is stored with mongoose. So just remove mongo and connect with mongoose
mongoose.connect('mongodb://localhost:27017/example');
var db = mongoose.connection;
db.once('open', function() {
console.log('OPEN');
});

Related

$lookup using mongoose Nodejs

I am using Nodejs(express) using Mongoose to connect with MongoDB.
Here two collections which where created using Mongoose schema in other API calls. For one API call request, i need to join these two collections and create the new collection (testalluser)which contains the new consolidated output.
And need to find all documents and send the output in the response to API call.
Note: I tried creating the Model also , but it not worked.
Query working fine inside DB .But in Mongoose, I am getting only empty array as the output .could you please help me to apply this logic in to Mongoose in NodeJS.
db.getallusers.aggregate([
{
"$lookup": {
"from": "getallusersroles",
"localField": "userRefID",
"foreignField": "userRefID",
"as": "role"
}
},
{ $merge: { into: "testalluser" } }
]).pretty()
Collection 1 Schema:getAllUsers
var mongoose = require('mongoose');
const getAllUsersDataSchema = new mongoose.Schema({
userRefID:String ,
userName:String,
divisionId: String,
divisionName:String,
emailId :String,
})
module.exports = getAllUsers = mongoose.model('getAllUsers',getAllUsersDataSchema );
Collection 2 getAllUsersRoles
var mongoose = require('mongoose');
const getAllUsersRolesDataSchema = new mongoose.Schema({
userRefID:String ,
skillRefId: String,
queueName:String,
})
module.exports = getAllUsersRoles = mongoose.model('getAllUsersRoles',getAllUsersRolesDataSchema);
Collection 3: testalluser(i Tried but i am not sure its needed)
var mongoose = require('mongoose');
const getAllCustomUsersDataSchema = new mongoose.Schema({
divisionId: String,
divisionName:String,
emailId :String,
role: Array,
userRefID:String ,
userName:String,
})
module.exports = testalluser = mongoose.model('testalluser',getAllCustomUsersDataSchema);
NodeJs Code:
const express = require('express');
const router = express.Router();
const request = require('request');
const config = require('../config');
const fs = require('fs');
const getAllUsers = require ('../db/getAllUsersListmodel');
const getAllUsersRoles = require ('../db/getetUserRolesListModel');
const testalluser =require('../db/getCustomUserListModel');
var mongoose = require('mongoose');
mongoose.connect ('mongodb://localhost/testdb',{ useUnifiedTopology: true , useNewUrlParser: true });
router.get('/', (req, res) => {
// token in session -> get user data and send it back to the Angular app
// Empty up the already existing documents inside this collection
testalluser.deleteMany({},()=>{
//Here i am trying to aggregate
getAllUsers.aggregate([
{
"$lookup": {
"from": "getallusersroles",
"localField": "userRefID",
"foreignField": "userRefID",
"as": "role"
}
},
{ $merge: { into: "testalluser" } } // creating this doc first time
]).
// Here i am trying to find the docs in this newly created collection
testalluser.find((err,getusers)=>{
if(err){
console.log(err)
}
else{
res.send(getusers);
console.log(getusers);
}
})
})
});
module.exports = router;

Getting error in nodejs when querying mongodb data?

I am getting error in nodejs console (see screenshot for more clarification).
In matches.js :
const mongoose = require('mongoose');
let Schema = mongoose.Schema;
const matchSchema = new Schema({
match_id:{
type:Number; <---- line 8
required:true;
},
season:{
type:Number;
required:true;
}
.....
.....
});
const matches = mongoose.model('matches', matchSchema);
module.exports = matches;
// Get matches
module.exports.getmatches = (callback, limit) => {
matches.find(callback).limit(limit);
}
In app.js :
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
matches = require('./models/matches');
mongoose.connection.openUri('mongodb://localhost:27017/IPL');
const db = mongoose.connection;
app.get('/home', (req, res) => {
matches.getmatches((err, match) => {
if(err){
throw err;
}
res.json(matches);
});
});
app.listen('5000');
console.log('Running on port 5000....')
I have made model folder which contains matches.js I am trying to access data from mongodb and when to display it as JSON data on API endpoint i.e localhost://5000/home
This is a basic JavaScript Object declaration error. A JSON Object should look like this,
{
match_id: {
type: Number, //see the comma there?
required: true
}
}
Instead of using ,, you have used ; which will throw a syntax error. use this instead,
const matchSchema = new Schema({
match_id: {
type:Number,
required:true
},
season: {
type:Number,
required:true
}
.....
.....
});
Also, your getmatches function requires a limit passed as the second parameter, you need to pass that as well in the code.

Trying to associate two children collections to a parent collection using populate

'Im trying to have an array of patients Objectids and an array of data(information about doctor) objectids inside the doctors collection. This is the beginning of the code then I got lost. I think I want to use something like this Doctor.find().populate('patients data'). Then if someone could show me how to access the information that would be great.
var express = require("express");
var app = express();
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/population")
var doctorSchema = new mongoose.Schema({
name : String,
patients : [{type : mongoose.Schema.Types.ObjectId, ref : "Patient"}],
data : [{type : mongoose.Schema.Types.ObjectId, ref : "Data"}]
})
var patientSchema = new mongoose.Schema({
name : String
})
var dataSchema = new mongoose.Schema({
income : String
})
var Doctor = mongoose.model("Doctor",doctorSchema );
var Patient = mongoose.model("Patient", patientSchema);
var Data = mongoose.model("Data", dataSchema);
var doc1 = new Doctor({"name" : "doc1"})
doc1.save(doc1, function(err, doc){
if(err){
console.log(err)
}else{
console.log("saved")
}
})
app.listen(3000, function(){
console.log("listening on 3000");
})
To access the information, the app should be able to receive requests; a 'get' method needs to be defined on the app object:
app.get('/:id', function(req, res) {
var doctorID = req.params.id;
Doctor
.findOne({_id: doctorID})
.populate('patients data')
.exec(function(err, doctor) {
if (err) throw err;
res.send(doctor);
});
});

Global objects with Node.js + Express

I'm studying Node.js + Express, coding a basic login example. My /login route is set inside the routes/login.js file:
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connectionpool = mysql.createPool({
host : 'localhost',
user : 'user',
password : 'pass',
database : 'database'
});
router.post('/', function(req,res){
connectionpool.getConnection(function(err, connection) {
if (err) {
console.error('CONNECTION error: ',err);
res.statusCode = 503;
res.send({
result: 'error',
err: err.code
});
} else {
// Do something
}
});
});
module.exports = router;
I was wondering: how can I make the mysql or the connectionpool visible in the entire application? I don't want to redeclare them on each route file I'll create. I'm looking something like an include or require method.
Any idea?
Create a separate module to act as an interface to retrieving SQL connections like so:
var mysql = require('mysql');
var connectionpool = mysql.createPool({
host : 'localhost',
user : 'user',
password : 'pass',
database : 'database'
});
exports.getConnection = function (callback) {
connectionpool.getConnection(callback);
};
Then in another file:
var connections = require('./connections');
connections.getConnection(function (err, c) {
// Use c as a connection
c.query("select * from table limit 10 ",function(err,rows){
//this is important release part
c.release();
if(!err) {
console.log(rows);
}
});
});

Building an api with Express and Waterline ORM

I'm trying to build an API with Express and Waterline ORM. The adapter I'm using is mongodb-adapter. The reason I'm trying to do this from outside Sails is that I want better understand the Waterline ORM so I can contribute to the Sails Couch Adapter. Here's what I got.
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
Waterline = require('waterline');
var mongoAdapter = require('sails-mongo');
app.use(bodyParser());
app.use(methodOverride());
mongoAdapter.host = 'localhost';
mongoAdapter.schema = true;
mongoAdapter.database = 'waterline-mongo';
app.models = {};
var User = Waterline.Collection.extend({
adapter:'mongodb',
// identity: 'user',
attributes: {
first_name: 'string',
last_name: 'string'
}
});
app.post('/users', function(req, res) {
console.log(req.body);
app.models.user.create(req.body, function(err, model) {
if(err) return res.json({ err: err }, 500);
res.json(model);
});
});
new User({ adapters: { mongodb: mongoAdapter }}, function(err, collection) {
app.models.user = collection;
// Start Server
app.listen(3000);
console.log('Listening on 3000');
});
So from what I understand collection will have the create/update/destory methods as defined by the Waterline API. However when I post to /users, I get a 'cannot call method "create" of undefined. The version of Waterline I'm using is 0.9.16. I'm probably setting this up wrong. Thanks in advance.
You'll have to add these instructions:
var orm = new Waterline();
var config = {
// Setup Adapters
// Creates named adapters that have have been required
adapters: {
'default': 'mongo',
mongo: require('sails-mongo')
},
// Build Connections Config
// Setup connections using the named adapter configs
connections: {
'default': {
adapter: 'mongo',
url: 'mongodb://localhost:27017/unparse'
}
}
};
var User = Waterline.Collection.extend({
identity: 'user',
connection: 'default',
attributes: {
first_name: 'string',
last_name: 'string'
}
});
orm.loadCollection(User);
orm.initialize(config, function(err, data) {
if (err) {
throw err;
}
app.models = data.collections;
app.connections = data.connections;
app.listen(3000);
});

Categories

Resources