Node.js with mongo - Rendering "object" instead the data inside the template? - node.js

Check my code...
var swig = require('swig');
var config = require('../config.json');
var mongojs = require('mongojs');
var ObjectId = mongojs.ObjectId;
var db = require('mongojs').connect(config.mongoDB, config.mongoDBcollections);
var roles;
db.lists.find({type:'roles'}).toArray(function(err, item) {
roles = item[0].data;
console.log(roles);
});
var sharetpl = swig.compileFile(__dirname +'/../html/register.html');
exports.index = function(req, res){
var output = sharetpl({
'title': 'Roles Itself',
'roles' : [roles]
});
res.send(output);
};
this is the console.log output...
[ { name: 'Web Developer', code: 'wdv' },
{ name: 'Web Designer', code: 'wds' },
{ name: 'System Archtect', code: 'sar' } ]
It's all okay, so far...but the html...
server side: <|-- {{roles}} -->
client html :
<|-- [object Object],[object Object],[object Object] -->
So, basically I'm stucked on it...It's rendering "[object Object]" on the client side instead the data itself :( pretty frustrated. Any clue ? ty !

roles is an array of Objects, so you need to refer to specific fields of each individual object in array.
if you are using Mustache the syntax will be as follows:
{{#roles}}
{{name}}, {{code}}
{{/roles}}

Related

Mongoose sub Docs CastError

I am new to MongoDB and MongooseJS. I'm also new to nodeJs.
I have an Angularjs project using Typescript. This project work with a "container" json, which itself contains some properties and a testList, which is a json object containing some properties and a fileList, containing an itemList.
So it's like this :
export class Container{
data:string="";
testList:Test[];
}
export class Test {
moredata:string="";
fileList:File[];
}
export class File {...}
etc.
I send this JSON to my nodejs server. I'm using bodyparser to get the json from the req.body object.
Server side, my mongoose Schema are exactly like my angularjs classes, so they look like this :
/*************** mongoose schemas **************/
// item.js
var mongoose = require('mongoose');
module.exports = mongoose.model('Item', {
Content : {type : Object, default: ''}
});
// file.js
var mongoose = require('mongoose');
var Item = require('./item');
var schema = new mongoose.Schema({
Data : {type : String, default: ''},
ItemList: {type: [Item], default:[]}
});
// test.js
var mongoose = require('mongoose');
var File = require('./file');
var schema = new mongoose.Schema({
Data: {type:String},
FileList: {type:[File], default:[]}
});
// container.js
var mongoose = require('mongoose');
var Test = require('./test');
var schema = new mongoose.Schema({
Name : {type : String, default: '', index:true, unique:true, required: true, dropDups:true},
Test : {type:[Test], default:[]}
});
If I try to create a new Container object (Mongoose object) and assign it the json from req.body, it bugs : CastError.
If I re-create each sub document from JSON and save the main doc, it bugs too : CastError.
I don't know how to achieve this. It worked before but my mongoose schema where using [mongoose.Schema.Types.Mixed] type for sub docs, and not the "real" types. Fact is, with Mixed I had no _id on sub docs, which I want.
Using real sub docs types, I can see in logs that the _id is created, but all the lists are empty.
Here is my nodejs code :
/*************** nodejs **************/
app.post('/api/container', bodyParser.urlencoded({extended:true}), bodyParser({limit:'50mb'}), bodyParser.json(), function(req, res) {
var test = req.body._test;
var testList = [];
var fileList;
var itemList;
var itemObj;
var fileObj;
var testObj;
for(var i in test){
fileList = [];
for(var j in test[i]._fileList){
itemList = [];
for(var k in test[i]._fileList[j]._itemList){
itemObj = new Item({
Content : test[i]._fileList[j]._itemList[k]._content
});
itemList.push(itemObj);
console.log('item pushed : ' + itemObj + ' and length : ' + itemList.length);
// logs gives info OK.
}
fileObj = new File({
Data: locales[i]._fileList[j]._data,
ItemList: itemList
});
fileList.push(fileObj);
console.log('file pushed : ' + fileObj);
// logs gives info NOK. The ItemList is empty : [], instead of a 70+ item list.
}
testObj = new Test({
Data: locales[i]._data,
FileList: fileList
});
testList.push(testObj);
console.log('test pushed : ' + i);
// once again, logs are NOK : the FileList is empty : []
}
// use mongoose to save the project in the database
new Container({
Name : req.body._name.toLowerCase().trim(),
Test: testList
}).save(function(err, container, count){
if(err){
console.log('erreur : ');
console.log(err);
// we enter here as we have this error :
/*
{ [CastError: Cast to undefined failed for value "
{
_id: 5727ebf95a76ff0011374928,
FileList: [],
Data: 'data'
},
{
_id: 5727ebf95a76ff0011374970,
FileList: [],
Data: 'other data'
}" at path "Test"]
message: 'Cast to undefined failed for value "
{ _id: 5727ebf95a76ff0011374928,\n FileList: [],\n Data: \'data\' },
{ _id: 5727ebf95a76ff0011374970,\n FileList: [],\n Data: \'other data\'}"
at path "Test"',
name: 'CastError',
type: undefined,
value: [{"_id":"5727ebf95a76ff0011374928","FileList":[],"Data":"data"},{"_id":"5727ebf95a76ff0
011374970","FileList":[],"Data":"other data"}],
path: 'Test' }
*/
res.status(403).json({error: 'error'});
} else {
console.log('saved ! ');
res.json(container);
}
});
});
I'm not used to post here, I'm more a reader :) Anyway if my post is not appropriated please inform me and I'll move / edit it correctly.
Thanks for your time.
Checked, and working !
So my error was to use the models of my objects in mongoose schema instead of their Schema.
I'm now exporting both models and schema on each object, and using schema for schema definitions, and models for requests. Finally rid of this bug ! :)
/* Mongoose object definitions */
// grab the mongoose module
var mongoose = require('mongoose');
var child = require('./child').schema; // getting the child schema
// define our parent model
var parentSchema = new mongoose.Schema({
Name : {type : String, default: ''},
ChildrenList: {type: [Child], default:[]}
});
var parentModel = mongoose.model('Parent', parentSchema);
// module.exports allows us to pass this to other files when it is called
module.exports = {
model: parentModel, // exporting model for requests
schema: parentSchema // exporting schema for others schema using "Parent"
};
And the code used for requests :
var Child = require('./models/child').model; // here using model
var Parent = require('./models/parent').model; // here using model
new Parent({
Name : req.body._name.toLowerCase().trim(),
ChildrenList : childrenList // variable defined somewhere
}).save(function(err, parent, count){
if(err){
res.status(403).json({error: 'too bad'});
} else {
res.json(parent);
}
});

Connecting Node.js to MongoDB using monk

I am trying to store the data written in jade to be stored in MongoDB using monk, but it is neither storing the data nor prompting any error
connecting to MongoDB code: (p1 is the name of the database)
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/p1');
index.js code to store in DB:
/* GET New User page. */
router.get('/addnew', function(req, res) {
res.render('addnew', { title: 'Add New Theatre' });
});
/* POST to Add User Service */
router.post('/addnew', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var theatrename = req.body.TheatreName;
var screen = req.body.Screen;
var latitude = req.body.Latitude;
var longitude = req.body.Longitude;
var city = req.body.City;
// Set our collection (Theatre is the name of the collection)
var collection = db.get('Theatre');
// Submit to the DB
collection.insert({
"TheatreName" : theatrename,
"Screen" : screen,
"Latitude" : latitude,
"Longitude" : longitude,
"City" : city,
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("Not adding into db.");
}
else {
// And forward to success page
res.send("Theatrelist");
}
});
});
module.exports = router;
This is my jade code:
extends layout
block content
h1= title
form#formAddUser(name="adduser",method="post",action="/adduser")
p Thearte Name:
input#inputName(type="text", name="ThearteName")
br
p Screen :
input#inputScreen(type="text", name="Screen")
br
p Latitude:
input#inputUserLat(type="text", name="Latitude")
br
p Longitude:
input#inputlong(type="text", name="Longitude")
br
p City:
input#inputCity(type="text", name="City")
br
br
button#btnSubmit(type="submit") submit
If I were you I will try to do this:
show in console that vars from "req.body.VAR" are send correctly.
For example
router.post('/addnew', function(req, res) {
console.log(req.body.Screen);
Then, I will try to add some data to the BD for example:
collection.insert({
"TheatreName" : "Fakename",
"Screen" : "Fakescreen",
"Latitude" : "0",
"Longitude" : "0",
"City" : "Fakecity",
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("Not adding into db.");
}
else {
// And forward to success page
res.send("Theatrelist");
}
});
If you can see the result in your BD, all is OK (else, is in connection or something similar).
I hope my answer will help you!

Express, Mongoose : OverwriteModelError : Cannot Overwrite 'xxxxx' model once compiled

I'm encoutering an error when using a Mongoose Model in my program.
I've did that in the beginning of my code :
var Schema = mongoose.Schema;
mongoose.connect('xxxxx');
I used a first schema called userSchema to connect/sign up a user.
I've this code, which should do a random on the field Bonus of my DB. But when I go to the randTest page, I have this error. How can I fix it ?
app.get('/randTest', function(req,res)
{
var bonusSchema = new Schema({
bonus : [String]
});
var bonusModel = mongoose.model('Plateau', bonusSchema);
var query = bonusModel.find(null);
query.exec(function (err, allBonus){
if(err) { throw err;}
var rand = Math.floor((Math.random() *allBonus.length));
var result = allBonus[rand-1];
});
res.render('randTest', {result: result});
});
In my Jade file I've just :
extends layout
block content
script.
alert({#result});
Move the bonusModel definition outside of app.get so that it's only called once:
var bonusSchema = new Schema({
bonus : [String]
});
var bonusModel = mongoose.model('Plateau', bonusSchema);
app.get('/randTest', function(req,res)
{
var query = bonusModel.find(null);
...
});

How to fetch data from mongodb and show using node.js

Following is my code to fetch data from a collection and show it on index page, but it is not giving the results.
Node Code-
var app = require('express')();
var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/test';
mongoose.connect(dbURI);
var testSchema = new mongoose.Schema({
name: String,
rollnum: String
});
var Test = mongoose.model('Test', testSchema);
app.get('/', function(req, res){
Test.find({},function(err, docs){
res.send('index',{docs:docs});
});
//res.send('test');
});
app.listen(3001);
However I check and have a collection in db like this -
Query fire - db.testinfo.find()
Output -
{
"_id": ObjectId("123456..78"),
"name": "test",
"rollnum": "XXXX"
}
After hitting the URL - http://127.0.0.1:3001/
This is the output I am getting -
{
"docs": []
}
However I was expecting to get the result of name, rollnum.
Please let me know what I am doing wrong.
When you register a model in Mongoose, it uses the pluralized, lower-cased model name as the name of the collection it's tied to. So because your model name is Test, the collection name is tests.
To tie the model to testinfo instead, pass that name as the third parameter to your model call:
var Test = mongoose.model('Test', testSchema, 'testinfo');

retrieving data from mongodb in jade template

I'm new to node and mongodb and am trying to render a database query in a template, but I get the error that the property is undefined:
Cannot read property 'firstname' of undefined
Here's my index.js file:
var dburl = 'localhost/olpdb';
var collections = ['users'];
var db = require('mongojs').connect(dburl, collections);
var currentUsers = db.users.find();
exports.index = function(req, res){
res.render('index', currentUsers);
};
In the index.jade template, I've got:
#{currentUsers.firstname}
I've queried the database separately and know that there is a record:
> db.users.find()
{ "firstname" : "andy", "lastname" : "johnson", "email" : "andy#johnson.com", "_id" : ObjectId("51adf8a8c58996cf0c000001") }
Can anyone help me with what I'm doing wrong? I'm trying to pass the object to the template so that I can extract the data.
In your code, currentUsers is probably an API object (a Query or similar). In order to use the query's result, you need to use a callback:
exports.index = function(req, res){
db.users.find(function(err, currentUsers) {
res.render('index', {
currentUsers: currentUsers
});
});
};
Now you can use the currentUsers array from your Jade template:
#{currentUsers[0].firstName}

Resources