JSON String appears to be blank in node js - node.js

I am trying to create web services using node js,express and mongoose.
this is my app.js file
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
GetData = require('./models/women');
mongoose.connect('mongodb://localhost/shopping');
var db = mongoose.connection;
app.get('/api/getCategories',function(req,res){
GetData.getCategory(function(err,getCategory){
if (err) {
throw err;
}
res.json(getCategory);
});
});
app.get('/',function(req,res){
res.send('Hi i am Madhura. Nice to Meet u. lets start creating web services');
});
app.listen(3000);
console.log('connected to Port 3000');
this is my women.js file
var mongoose = require('mongoose');
var categorySchema = mongoose.Schema({
name:{
type: String,
required: true
}
});
var Category = module.exports = mongoose.model('',categorySchema);
module.exports.getCategory = function(callback,limit){
Category.find(callback).limit(limit);
}
I am unable to understand this line
var Category = module.exports = mongoose.model('',categorySchema);
I have left this ' ' blank because I wanted to know what parameter is passed here
I watched a video about this, and could not find a conclusion. however, I simply followed the video and run the code. but my output is coming to be a null JSONArray "[]". Please tell me what am i doing wrong.

var mongoose = require('mongoose');
var categorySchema = mongoose.Schema({
name:{
type: String,
required: true
}
});
var Category = mongoose.model('Category',categorySchema);
module.exports.getCategory = function(callback,limit){
Category.find(callback).limit(limit);
}
The part you have made '' contains the mongoose model name that you can use to refer the respective MongoDB collection. you can imagine a model name as replacement of db.collectionname for MongoDB. I have updated the codebase

Related

Unable to connect to mongoDB client using mongoose

I am a beginner in mongoose and mongo DB. When I am trying to connect to mongoDB using mongoose , running the app.js file with the help of node app.js the process is struck.
I am not getting any output. When I am checking the database then also the database is not created.
Can anyone please tell me where I am going wrong?
This is my code:
const mongoose = require('mongoose');
var conn = mongoose.connect('mongodb://localhost:27017/my_database', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const peopleSchema = new mongoose.Schema ({
name: String,
age: Number
});
const People = mongoose.model("People",peopleSchema);
const people = new People({
name : "Umang",
age: 25
})
people.save();
Try the following command in your command prompt
npm install express
Then add the following code snippet.
const mongoose = require('mongoose');
const express = require('express')
const app = express()
var conn = mongoose.connect('mongodb://localhost:27017/my_database', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const peopleSchema = new mongoose.Schema({
name: String,
age: Number
});
const People = mongoose.model("People", peopleSchema);
const people = new People({
name: "Umang",
age: 25
})
people.save();
app.listen(3000, function () {
console.log('Node server listening on port 3000');
})
I have tested it and it is working.
Make sure MongoDb is connected

gridfs-stream and mongoose >= 4.11.0 connection settings

I have been using gridfs-stream with older versions (<4.11.0) of mongoose with the following settings:
var grid = require("gridfs-stream");
var mongoose = require("mongoose");
mongoose.connect(connectionString);
grid.mongo = mongoose.mongo;
var gfs = grid(mongoose.connection.db);
All works fine with these settings. After the update to mongoose 4.11.11 the mongoose connection setting should be changed to (3rd line):
mongoose.connect(connectionString, {useMongoClient: true});
However, now mongoose.connection.db is no longer defined. How should the above code be changed to make it work again? Many thanks.
I found a solution which makes use of deasync and with minimal changes to all my existing code. However it does not look ideal so any suggestions will be greatly appreciated:
var grid = require("gridfs-stream");
var mongoose = require("mongoose");
var deasync = require("deasync");
//Connect to mongodb
mongoose.Promise = global.Promise;
mongoose.connect(connectionString, {useMongoClient: true});
//Get the connection setting
var getConnDb = function () {
var connDb;
mongoose.connection.then(function (conn) {
connDb = conn.db;
});
while (connDb === undefined) {
deasync.runLoopOnce();
}
return connDb;
};
//Set gridfs-stream connection
grid.mongo = db.mongo;
var gfs = grid(getConnDb());

Why I cant retrive data from mongodb in my simple web application?

I am trying to connect mongodb to my express nodejs web application. I am fresh new to nodejs. I am following this tutorial video but I couldn't complete it due to the connection of mongodb.
the app.js code I have:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
Genre = require('./models/genre');
let conn = mongoose.connection;
conn.openUri('mongodb://localhost/bookstore');
conn.on('error', err => console.error('mongodb connection error',
err));
conn.on('connected', () => console.info(`Connected to mongodb`));
conn.on('disconnected', () => console.info('Disconnected from
mongodb'));
app.get('/', function(req, res){
res.send('Hello World');
});
app.get('api/genres', function(req , res){
Genre.getGenres(function(err, genres){
if(err){
throw err;
}
res.json(genres);
})
});
app.listen(3666);
console.log('Server Running On http://localhost:3666');
and this is the genre.js
var mongoose = require('mongoose');
var genreSchema = mongoose.Schema({
name:{
type: String,
requires: true
},
create_date:{
type: Date,
default: Date.now
}
});
var Genre = module.exports = mongoose.model('Genre', genreSchema);
module.exports.getGenres = function(callback, limit){
Genre.find(callback).limit(limit);
}
and this is a picture of the database in the terminal
https://i.stack.imgur.com/S3gFb.png
And the information in genres collection in the database
https://i.stack.imgur.com/sJFE6.png
Once I open the main page I get the Hello World but once I add api/genres which I should get the data from mongodb I get this error
https://i.stack.imgur.com/B4c8o.png
and this is the files structures
https://i.stack.imgur.com/okHIN.png
I know this is a basic question but I couldnt figured out I check on google there are others way to connect to the database but I need to know why this particular way which I just followed from the tutorial video havent worked.
As you noticed I am a new to nodejs web development so if you could suggest websites or youtube channels to get me start it I would appreciate it.
It seems that it is not a db connection problem. Route matching http://localhost:3666/api/genres is not found in your application. Replace api/genres with /api/genres and I guess everything will work properly

Mongoose Error when trying to load my model from a different file

I'm getting an error for trying to include a mongoose model written in a separate file.
throw new mongoose.Error.MissingSchemaError(name);
MissingSchemaError: Schema hasn't been registered for model "Cart".
Use mongoose.model(name, schema)
Within my server.js file my mongo models are defined before I call my routes. Which I've looked around and found defining your models after the routes are the cause of this error but that's not my case.
//Require db config
require('./app_api/config/model.js');
//Require routes config
var routesAPI = require('./app_api/config/routes.js')
var app = express();
Within my model.js file I require my separate schemas.
var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/followdata';
mongoose.connect(dbURI);
// CONNECTION EVENTS
mongoose.connection.on('connected', function() {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error', function(err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function() {
console.log('Mongoose disconnected');
});
// SCHEMA DECLERATION
require('../models/user');
require('../models/userCart');
So I'm not really sure what the problem is.
This is how I try to bring in my cart model into my user model schema.
var mongoose = require( 'mongoose' );
var jwt = require('jsonwebtoken');
var crypto = require('crypto');
var Cart = mongoose.model('Cart');
var Schema = mongoose.Schema;
var userSchema = new Schema({ ......... });
And within my userCart.js file I export it properly.
module.exports = mongoose.model('Cart', cartSchema);
You need to require in your Cart schema if you want to use it in your User model schema.
So, you would need var Cart = require('yourPathToCart/cart') instead of var Cart = mongoose.model('Cart') (the previous line of code is attempting to create a new model named Cart and this is where your error is coming from) in your User model schema file.

Creating a collection schema in a mongolab mongodb database from node.js

I'm new to node.js and mongodb.
I'm trying to create a schema for a User collection in a mongolab mongodb database from a node.js app with the code below. The code does not seem to be failing (at least, I get no error messages), but I don't see any indication that it is succeeding either. That is, when I go to mongolab and look at my database, I don't see that any schema was created - https://dzwonsemrish7.cloudfront.net/items/01263Y1c312s233V0R17/mongodb-schema.png?v=7fdc20e3.
Can someone explain what I might be doing wrong, or how I can verify that my code succeeded and a schema was, in fact, created for my collection?
// file: app.js
var express = require('express'),
http = require('http'),
mongoose = require('mongoose');
var app = express(),
port = 3000;
// Connect to database in the cloud (mongolab)
mongoose.connect('mongodb://username:password#ds041344.mongolab.com:41344/stockmarket');
// Create a schema for User collection
mongoose.connection.on('open', function () {
console.log(">>> Connected!");
var UserSchema = new mongoose.Schema({
username: {type: String, unique: true},
password: String
});
var UserModel = mongoose.model('User', UserSchema);
});
app.get('/', function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!\n');
});
http.createServer(app).listen(port, function(){
console.log("Express server listening on port " + port + " ...");
});
You must insert a document first. Schemas are not explicitly defined in mongodb. Once you insert a document, the collection will automatically be created and you will see it in the mongolab console.
Example from http://mongoosejs.com/
var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'test');
var schema = mongoose.Schema({ name: 'string' });
var Cat = db.model('Cat', schema);
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
if (err) // ...
console.log('meow');
});
after the save call above the collection will be created
Data in MongoDB has a flexible schema. Documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.

Resources