MongoDB - Getting error while connect with local data base - javascript

I am trying to create a User list when user submit their details. In app.js I have the function for that.
like this:
app.post('/addList', userList.submit);
I am calling my function which is nested in userList.submit:
var sendList = require('../model/model');
exports.list = function(req, res){
res.send("respond with a resource this is from list file");
};
exports.addList = function(req, res, next){
res.render('index', {title:'title from list.js'});
};
exports.submit = function(req,res,next){
var name = req.body.name,
dept = req.body.dept;
sendList.create({
name:name,
dept:dept
}, function(error){
console.log('Erros is ', error);
if (error) return next(error);
res.redirect('/');
});
};
In the model folder, model.js has the function as follows:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/user_list');
var schema = new Schema({
name:String,
dept:String
});
module.exports = mongoose.model('User', schema);
But I am getting error saying:
var schema = new Schema({
^
ReferenceError: Schema is not defined
What is this mean? where I made the mistake? any one figure out and help me to solve this?

Schema is defined as a property of mongoose. It's not there in the global scope of nodejs.
var schema = new mongoose.Schema({
name:String,
dept:String
});

Schema is part of an application or is a property of mongoose. It has nothing to do with db, it's only mapping db into js objects.
you have to change the code : = new mogoose.schema ({ what ever you want ..

Related

Mongoose how to use same schema for different collections, but still be able to update those collections individually

I have 2 collections that I declared in my comments.model file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
require('./util');
var currentDate = new Date().getDate();
var currentMonth = new Date().getMonth()+1;
var currentYear = new Date().getFullYear();
var battleFieldOneCommentsSchema = new Schema( {
user_name: {type: String},
comment: {type: String},
date_created: {type: String, default: String(currentDate+"/"+currentMonth+"/"+currentYear)},
likes: {type: Number, default: 0},
dislikes: {type: Number, default: 0}
});
module.exports = mongoose.model('battlefieldOne_Comments', battleFieldOneCommentsSchema);
module.exports = mongoose.model('another_game_Comments', battleFieldOneCommentsSchema);
I have an index.js file that has API's to insert comments into the database:
var battlefieldOne_Comments = require('../models/comments');
var anotherGame_Comments = require('../models/comments');
router.post('/add_battlefieldOne_Comment', function(req, res, next) {
comment = new battlefieldOne_Comments(req.body);
comment.save(function (err, savedComment) {
if (err)
throw err;
res.json({
"id": savedComment._id
});
});
});
router.post('/add_anotherGame_Comments', function(req, res, next) {
comment = new anotherGame_Comments(req.body);
comment.save(function (err, savedComment) {
if (err)
throw err;
res.json({
"id": savedComment._id
});
});
});
module.exports = router;
When I use that API, it inserts the same comment into both collections on the database. I know this is because both comments variables in the index.js file require the same file. Is there a way to fix this, because I don't want to make a new model file for each schema. I am new to nodejs and mongoose, so this might be a silly question, but is there a way to define a single schema and use that schema for a lot of collections, while still being able to update those collections separately and independently?
The way you are exporting and requiring your models in index.js won't have the effect you want.
When you use module.exports like that you're not giving the values you're exporting a name, so when require is called on that file, you'll end up requiring the same value for both of your variables.
What you wanna do here is set your models to different variables and then export those:
var battlefieldOneComments = mongoose.model('battlefieldOne_Comments', battleFieldOneCommentsSchema);
var anotherGameComments = mongoose.model('another_game_Comments', battleFieldOneCommentsSchema);
module.exports = {
battlefieldOneComments : battlefieldOneComments,
anotherGameComments : anotherGameComments
}
After that you require them by accessing those in index.js:
var battlefieldOne_Comments = require('../models/comments').battlefieldOneComments;
var anotherGame_Comments = require('../models/comments').anotherGameComments;
That way you're not requiring the same model for both variables and it should save your comments on different collections.

MongooseJS object undefined inside callback function

I'm trying to write an endpoint for an API that will return all orders for a given user. My issue is that when I try to query the database using mongoose's findById function, the 'user' object is undefined in the callback function and I can't query the orders subdoc. To add to the confusion, I can get it to work if I don't use a callback function, but then I don't have proper error handling.
var mongoose = require('mongoose');
var router = express.Router();
var order_model = require('../models/order');
var user_model = require('../models/user');
router.get('/:userid/order/', function (req, res) {
// This works???
var u = user_model.findById(req.params.userid);
res.json(u.orders);
});
The following code throws the error "TypeError: Cannot read property 'orders' of undefined".
var mongoose = require('mongoose');
var router = express.Router();
var order_model = require('../models/order');
var user_model = require('../models/user');
router.get('/:userid/order/', function (req, res) {
// This throws an error.
user_model.findById(req.params.userid).then(function (err, user) {
if (err) {
res.send(err);
}
res.json(user.orders);
});
});
user.js
var mongoose = require('mongoose');
var ordersSchema = require('./order').schema;
var userSchema = new mongoose.Schema({
name: String,
email: String,
showroom: String,
orders: [ordersSchema]
});
module.exports = mongoose.model('User', userSchema);
order.js
var mongoose = require('mongoose');
var lineItemsSchema = require('./lineitem').schema;
var ordersSchema = new mongoose.Schema({
trackingNumber: Number,
lineItems: [lineItemsSchema]
});
module.exports = mongoose.model('Order', ordersSchema);
Any help / explanation of this behavior would be appreciated. Thanks!
The first parameter of the then callback is user, not err.
Either use a traditional callback:
user_model.findById(req.params.userid, function (err, user) {
if (err) {
res.send(err);
return; // Need to return here to not continue with non-error case
}
res.json(user.orders);
});
Or chain a call to catch on the promise to separately handle errors:
user_model.findById(req.params.userid).then(function (user) {
res.json(user.orders);
}).catch(function(err) {
res.send(err);
});
I usually query like this, it work perfect :
user_model.find(_id : req.params.userid)
.exec((err, user) => {
if(err){
//handle error
}
return res.status(200).json(user.orders);
})
});

Why is the model not binding properly in nodejs?

I am developing a web app using nodejs, angular, mongo. Having a weird problem. Model is not binding properly from json object.
this is my Schema.
var mongoose = require('mongoose');
var productSchema = new mongoose.Schema({
name : {type: String},
imageURL : {type: String, default: '/'},
created : {type: Date, default: Date.now}
});
module.exports = mongoose.model('product', productSchema);
And I am passing the product using POST to my index.js.
router.post('/pictures/upload', function (req, res, next) {
uploading(req, res, function(err){
if (err) {
console.log("Error Occured!");
return;
}
var product = new productModel(req.body.pName);
product.imageURL = req.file.path;
product.update(product);
res.status(204).end();
});
var product only consists of _id, created, imageURL. not the name property.
But console.log(req.body.pName) prints out {"_id":"56d80ea79d89091d21ce862d","name":"sunny 2","__v":0,"created":"2016-03-03T10:15:03.020Z","imageURL":"/"}
Its not getting the name property. Why is that???
Please advise.
Found the Solution. It wasn't binding properly because content-type was in multipart/form-data. I had to parse the jSON object, like this:
var product = new productModel(JSON.parse(req.body.pName));
pName had the values in a string.
Hope this helps someone.
Try this way, You just creating instance of Product object and then updating.
var Product = mongoose.model('products');
uploading: function(req, res) {
// console.log(req.body); find your object
// in your case it looks req.body.pname
var product = new Product(req.body.pname);
product.imageURL = req.file.path;
product.save(function (err, product) {
if (err){
console.log(err);
}else{
res.status(204).end();
// it returns json object back - callbcak
// res.json(product);
}
})
},

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

mongoose: TypeError: [function name] is not a function. when trying to create mongoose instanse

I'm writing a web application with MEAN stack, and I'm getting a headache with mongoose instance.
Here are (piece of) my codes:
my route
var express = require('express');
var router = express.Router();
var accDocService = require('../services/accdoc-services');
router.post('/dailybook', function(req, res) {
accDocService.addAccDoc(req.body, function(error) {
if (error) throw error;
});
});
accdoc-service.js
var accDoc = require('../models/accdoc').accDoc;
console.log(typeof accDoc);
exports.addAccDoc = function(accDoc, next) {
var newAccDoc = new accDoc({
number: '45645'
});
newAccDoc.save(function(error) {
if (error) throw error;
console.log("doc created");
});
};
accdoc.js (the model file)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var accDocSchema = new Schema({
number: String
});
var accDoc = mongoose.model('accDoc', accDocSchema);
module.exports = {
accDoc: accDoc
};
After sending the post request, I'm getting TypeError: accDoc is not a function
Also, console.log(typeof accDoc); in second file, returns function.
EDIT 1
In accdoc-services, if I move var AccDoc = require('../models/accdoc'); to the addAccDoc function, everything works fine.
Am I missing some node.js stuff here? I'm watching a tutorial video from Lynda that there is not some scope problem like this.
here is an image from Lynda tutorial
You are missing the new keyword for creating a model instance of accDoc
var accDoc = require('../models/accdoc').accDoc;
console.log(typeof accDoc);
exports.addAccDoc = function(accDoc, next) {
var newAccDoc = new accDoc({ // HERE new was missing!
number: '45645'
});
newAccDoc.save(function(error) {
if (error) throw error;
console.log("doc created");
});
};

Categories

Resources