How to show mongodb data as JSON? (NodeJS) - json

So what I'm asking is how I would show my MongoDB data as JSON on a seprate page? So far I have a database called 'movies' which has a table that contains a bunch of movie titles, rating and stock.
As seen here:
{ "_id" : ObjectId("55e579d30bb58af007d4d8f3"), "movieTitle" : "Iron Man", "rating" : "Excellent", "stock" : "Yes", "sort" : "iron man", "__v" : 0 }
{ "_id" : ObjectId("55e59c3d1d19a3d20ae67a9c"), "movieTitle" : "A Bittersweet Life", "rating" : "Poor", "stock" : "Yes", "sort" : "a bittersweet life", "__v" : 0 }
{ "_id" : ObjectId("55e59c441d19a3d20ae67a9d"), "movieTitle" : "A Team", "rating" : "Okay", "stock" : "No", "sort" : "a team", "__v" : 0 }
I also have the page I want the json to be displayed on:
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('data', {});
});
module.exports = router;
Schema:
var movieSchema = new Schema({
movieTitle: {
type: String,
required: true
},
rating: {
type: String
},
stock: {
type: String,
required: true
},
sort: {
type: String
}
});
Can someone help me out?

I think you could do something like this:
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
var movieSchema = new Schema({
movieTitle: {
type: String,
required: true
},
rating: {
type: String
},
stock: {
type: String,
required: true
},
sort: {
type: String
}
});
var Movie = mongoose.model('Movie', movieSchema, 'movies');
mongoose.connect('localhost', function(err, res){
})
/* GET home page. */
router.get('/', function(req, res, next) {
Movie.find({}, function(err, movies) {
res.render('data', movies);
})
});
module.exports = router;

For those who want to see how I got it working:
/* GET home page. */
router.get('/', function(req, res, next) {
// Get Movie schema for use
var Movie = mongoose.model('movie');
// Query all records using aggregate
Movie
.aggregate()
.match({})
.sort({ sort: 1 })
.exec(function(err, movies) {
// Handle errors
if (err) {
return res
.status(500)
.json({
error: err
});
}
// Manipulate movies to tidy up keys
movies.forEach(function (movie) {
movie.id = movie._id;
delete movie._id;
delete movie.__v;
delete movie.sort;
});
return res.json(movies);
});
});

Related

iterating objects as array of objects sent through postman tool and saving in db

this is the value i'm sending through postman tool
{
"name" :[
{
"first_name" : "antony",
"second_name" : "grijan"
},{
"first_name" : "suresh",
"second_name" : "muthu"
}],
"allergy" : [
{
"condition" : "headache"
},
{
"condition" : "toothache"
}],
"communication" : [
{
"address" : "no 21 big street",
"phone" : "84"
},
{
"address" : "no 43 small street",
"phone" :"87"
}]
}
I got the value in my control layer and i'm trying to save it in my mongodb using mongoose, my model code is
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var patientSchema = new Schema({
name: {
first_name : { type : String, default : ''},
second_name : { type : String, default : ''}
},
allergy : {
condition : {type : String, default : ''}
},
communication : {
address : {type : String, default : ''},
phone : {type : String, default : ''}
}
});
var patients = mongoose.model('Patients',patientSchema);
module.exports = patients;
My service layer code where i'm iterating is
var addDao = require('../dao/dao');
var async = require('async');
module.exports.addPatient = function(detail,callback) {
async.mapValues(detail,function(value,key,callback){
addDao.addPatient(value,function(data){
console.log(data);
console.log("calling");
callback(null, data);
})
}, function(err, result) {
// result is now a map of results for each key
console.log("inside func",result);
callback(result);
}
);
}
I have a console.log() in my service layer but it gives me only empty values, i think there is something wrong either with my model code or my iteration in my service layer!

Insertion issue in Json Array object mongodb with Nodejs?

I am new to mongodb , I have below Json structure in mongodb ,
{
"_id" : ObjectId("59d62452a164b51d64b714c2"),
"folderName" : "Avinash 1234",
"tag" : "search",
"ismainFolder" : true,
"innerFolder" : [
{
"ismainFolder" : false,
"foldername" : "Test12",
"_id" : ObjectId("59d72246e66adf2cfcfdd6e6")
}
],
"innerFiles" : [
{
"filelocation" : "",
"isFolder" : false,
"filename" : "Penguins.jpg",
"_id" : ObjectId("59d7223de66adf2cfcfdd6e5")
},
{
"filelocation" : "",
"isFolder" : false,
"filename" : "Desert.jpg",
"_id" : ObjectId("59d72ff4e66adf2cfcfdd6ec")
},
{
"filelocation" : "",
"isFolder" : false,
"filename" : "Hydrangeas.jpg",
"_id" : ObjectId("59d731dfe66adf2cfcfdd6ed")
},
{
"filelocation" : "",
"isFolder" : false,
"filename" : "Chrysanthemum.jpg",
"_id" : ObjectId("59d73252e66adf2cfcfdd6ee")
}
],
"__v" : 0
}
For innerFiles array i need to insert the Tag field depending on the id ("_id" : ObjectId("59d7223de66adf2cfcfdd6e5")) . I used following nodeJs code but it adding as a new object . Please give me the solution .
exports.addTagForSearch = function (req, res, next) {
var tagDetails = req.body.tagDetails;
console.log("tagDetails", tagDetails);
console.log("tagDetails", tagDetails._id);
Repository.find({ _id: tagDetails._id, }, { innerFiles: { $elemMatch: { _id: tagDetails._id } } },function (err, response) {
$push: {
innerFiles: {
"tagName": tagDetails.tagname,
}
//"filelocation": tagDetails.filelocation
}
}, { upsert: true, new: true }, function (err, post) {
if (err) return next(err);
return res.status(200).json("success");
});
}
but above code inserting as a new object , Please give me solution please .
First I need to create a database for that I had a config.js file . Here is the code
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/innerFiles'
}
Next create a models folder and keep this order.js in it
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var folderSchema=new Schema({
ismainFolder:{
type:String,
//required:true,
default:''
},
foldername:{
type:String,
//required:true,
default:''
}
});
var innerSchema=new Schema({
filelocation:{
type:String,
//required:true,
default:''
},
isFolder:{
type:String,
//required:true,
default:''
},
filename:{
type:String,
//required:true,
default:''
}
});
var main= new Schema({
folderName:{type:String},
tag:{type:String},
ismainFolder:{type:String},
innerFolder:[folderSchema],
innerFiles:[innerSchema]
},{ strict: false });
var Order= mongoose.model('main', main);
// make this available to our Node applications
module.exports = Order;
Next create a routes folder and keep this orderRouter.js file in it
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Orders = require('../models/orders');
var app = express();
var orderRouter = express.Router();
orderRouter.use(bodyParser.json());
orderRouter.get('/get',function (req, res, next) {
Orders.find({}, function (err, order) {
if (err) throw err;
res.json(order);
});
})
orderRouter.post('/post',function (req, res, next) {
Orders.create(req.body, function (err, order) {
if (err) {
res.status(400).send('Bad request');
}
else{
console.log('order created!');
var id = order._id;
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Added the order with id: ' + id);
}
});
})
orderRouter.get('/:orderId',function (req, res, next) {
Orders.findById(req.params.orderId, function (err, order) {
if (err) {
res.status(404).send('OrderId not found');
}
else{
res.json(order);
}
});
})
orderRouter.put('/addingField',function(req,res){
//var tagDetails = req.body;
console.log("tagDetails:"+req.body.subId);
console.log("tagname:"+req.body.tagname);
Orders.update(
{_id:req.body.mainId,'innerFiles._id':req.body.subId},
{$set:{'innerFiles.$.tagName':req.body.tagname}},
function (err, article) {
if (err) return console.log(err);
res.json(article);
});
});
app.use('/orders',orderRouter);
app.use(express.static(__dirname+'/public'));
module.exports = orderRouter;
Next create a app.js file this is the server code
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log("Connected correctly to server");
});
var orderRouter = require('./routes/orderRouter');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// passport config
app.use(passport.initialize());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/orders',orderRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
app.listen(3000,function(){
console.log("Server listening on 3000");
});
module.exports = app;
And run the server as node app.js.You can post data using this api http://localhost:3000/orders/post you need to use post method.Here is the sample input example for posting
{
"folderName" : "Avinash 1234",
"tag" : "search",
"ismainFolder" : "true",
"innerFolder" : [
{
"ismainFolder" : "false",
"foldername" : "Test12"
}
],
"innerFiles" : [
{
"filelocation" : "a",
"isFolder" : "false",
"filename" : "Penguins.jpg"
},
{
"filelocation" : "b",
"isFolder" : "false",
"filename" : "Desert.jpg"
},
{
"filelocation" : "c",
"isFolder" : "false",
"filename" : "Hydrangeas.jpg"
},
{
"filelocation" : "d",
"isFolder" : "false",
"filename" : "Chrysanthemum.jpg"
}
]
}
and here is the image for it
After posting data check that your data is stored in db or not.Here whatever the id I am giving in response is mainId . For that run this api http://localhost:3000/orders/get use get method for this. Collect the sub document id which is subId in our code.Sample Image for getting
After this here is the task of adding a new field to sub document for that use this api http://localhost:3000/orders/addingField and you need to use put method for this.Here is the input example
{
"mainId":"59dca6aff968a98478aaaa96",
"subId":"59dca6aff968a98478aaaa9a",
"tagname":"hello"
}
And Image for it
After completion of all these steps check into db.Here is the sample image for
it
That's it. Hope it helps.

saving in the database variable as ObjectID() MongoDB, NodeJS

I created function which is adding people_id inside array of given card. But there is problem that inserted id is always not as an objectId() where I just need it to be saved as objectId.
When id is added to array i I'm sending whole variable board JSON to nodejs API where is executed function findOneAndUpdate. And here is problem because after saved this arrays is not objectID in Author. Can someone tell me how to make it?
JSON board
{
"_id" : ObjectId("59e096a7622a3825ac24f343"),
"name" : "1",
"users" : [
ObjectId("59cd114cea98d9326ca1c421")
],
"lists" : [
{
"list" : "1",
"cards" : [
{
"name" : "2",
"Author" : [
"59df60fb6fad6224f4f9f22d",
"59df60fb6fad6224f4f9f22d",
"59df60fb6fad6224f4f9f22e"
]
},
{
"name" : "3",
"Author" : []
}
]
},
{
"list" : "fea",
"cards" : [
{
"name" : "card",
"Author" : []
}
]
}
],
"__v" : 0 }
Router:
router.post('/add/member', function (req, res, next) {
console.log(req.body)
Board.findOneAndUpdate({ _id: req.body._id },
{
$set: {
lists : req.body.lists
}
},
{
upsert: true
},
((cards) => {
res.send(cards)
})
)
});
model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoardSchema = new Schema({
name: { type: String, maxlength: 20 },
lists : { type: Array },
users : [{ type : Schema.Types.ObjectId, ref: 'User' }],
});
module.exports = mongoose.model('Board', BoardSchema);
And here is function with adding poeple
$scope.addMemberToCard = (indexList, indexCard, member) => {
$scope.board.lists[indexList].cards[indexCard].Author.push(member);
console.log( $scope.board.lists[indexList].cards[indexCard].Author)
return ApiService.staff.addMemberToCard($scope.board).then(function () {
})
}
You could use the mongoose Types ObjectID method and then transform the string sent into an ObjectID.
const id = new new mongoose.Types.ObjectId(Author);

How to get sub document only in mongoose?

I'm trying to extract only sub document from an array has the following schema :
const UserSchema = Schema({
name: {
type: String
},library:[{
story:{type: Schema.Types.ObjectId,ref: 'Story'}
}],
});
i tried to use :
module.exports.getUserStories = function(userId, callback){
User.findOne({_id: userId },callback)
.select('library.story')
};
and it gives this result :
{
"_id": "5949615072e15d2b34fa8f9d",
"library": [
{
"story": "592ae46cf2a0ba2b208cb092"
},
{
"story": "592ae608df26d80790092fe9"
},
{
"story": "592ae46cf2a0ba2b208cb092"
}
]
}
but what i'm expecting to get is only this :
[
{
"story": "592ae46cf2a0ba2b208cb092"
},
{
"story": "592ae608df26d80790092fe9"
},
{
"story": "592ae46cf2a0ba2b208cb092"
}
]
I already tried to use double selection like :
module.exports.getUserStories = function(userId, callback){
User.findOne({_id: userId },callback)
.select('library.story')
.select('story')
};
But is gives the same result
Try this one :
module.exports.getUserStories = function(userId, callback){
User.find({_id: userId },{'library.story'}).then(function(user){
if(user){
callback(user.library);
}});
};
Docs here
This output is expected to return by "select" but simply you can prepare the returned data to be as you need as following:
User.findOne({_id: userId }).select('library').then(function(result){
if(result){
//If there is returned item
var stories = result.library;
//Continue ...
}
},function(error){
//Error handling
})

Backbone underscore where inside json

I have an app in backbone where I want to find inside a Json record where hotel_id = 1 for example.
I have done in this mode:
var Room = Backbone.Model.extend();
var Rooms = Backbone.Collection.extend({
model:Room,
url : "includes/rooms.json"
});
var RoomView = Backbone.View.extend({
template: _.template($("#hotel-list-template").html()),
initialize: function(){
this.render();
},
render: function(){
this.bindRoomToHotel();
var element = this.$el;
element.html('');
// $(this.el).html(this.template({hotels: this.collection.models}));
},
bindRoomToHotel: function() {
allRooms = new Rooms();
allRooms.fetch();
rooms = allRooms.where({'hotel_id' : 1});
console.log(rooms);
}
});
I have cut many parts but the problem is inside bindRoomHotel when I make the where function return me empty.
This is my json:
[
{
"id" : "r1",
"hotel_id" : "1",
"name" : "Singola"
},
{
"id" : "r1_1",
"hotel_id" : "1",
"name" : "Doppia"
},
{
"id" : "r2",
"hotel_id" : "2",
"name" : "Singola"
},
{
"id" : "r2_1",
"hotel_id" : "2",
"name" : "Tripla"
}
]
How to find record with hotel_id=1?
Pretty sure you don't need quotes round the attribute name, maybe try this
rooms = allRooms.where({ hotel_id : 1 });
edit: I don't see where you are initializing those objects in the code you have provided, i'd expect to see something like this.
var Room = Backbone.Model.extend();
var Rooms = Backbone.Collection.extend({
model: Room,
url: "includes/rooms.json"
});
var RoomView = Backbone.View.extend({
template: _.template($("#hotel-list-template").html()),
initialize: function () {
this.render();
},
render: function () {
this.$el.html(_.template(this.template, this.collection.where({ hotel_id: 1 }));
}
});
var roomsCollection = new Rooms();
var roomView;
roomsCollection.fetch({
success: function ( rooms ) {
roomView = new RoomView( collection: rooms );
}
});