0

I followed this article in MongoDB Docs and have created a similar one-to-many relationship, only referencing the "publisher" by id value in the children. The data structure is as follows, publisher_id being the working piece here:

{
   _id: 123456789,
   title: "MongoDB: The Definitive Guide",
   author: [ "Kristina Chodorow", "Mike Dirolf" ],
   published_date: ISODate("2010-09-24"),
   pages: 216,
   language: "English",
   publisher_id: "oreilly"
}

{
   _id: 234567890,
   title: "50 Tips and Tricks for MongoDB Developer",
   author: "Kristina Chodorow",
   published_date: ISODate("2011-05-06"),
   pages: 68,
   language: "English",
   publisher_id: "oreilly"
}

If I have a page, for example, with all O'Reilly books, how can I return those objects with the proper publisher_id. Is this typically done on the front-end or the back-end?

Himmel
  • 3,629
  • 6
  • 40
  • 77

1 Answers1

0

Yes, you would typically query the Mongo database on the back end (node.js) using the Mongoose middleware. You can also use the MongoDB plugin. You can send your query from your Angular front end with an http call, which node routes to your server side controller. Your server side book.controller file would look like this:

var mongoose = require('mongoose'),
Books = mongoose.model('Books')

exports.findBooks = function(req,res){
    var query = {publisher_id:req.body.publisherName};
    Books.find(query,function(err,bookResults){
        if (err){
            return res.status(400).send({message: err})
        } else {
            res.status(200).send({books: bookResults});
        }
    })
};

Your node.js route could look like this:

 var controller = require('./controllers/book.controller.js'),
        express = require('express'),
        app = express(),
        router = express.Router();

 router.post('/find/books',controller.findBooks);

Your Angular front end file would make a call like this:

$http.post('/find/books',{publisherName: $scope.publisher})
        .success(function(res){
            //handle data received
        })

This is an answer for a basic query of data, it assumes the user would know what the publisher ID is on the front end. You could query the list of publisher ids and names on page load and let them choose from a drop down, then run this query. If you are looking for joins, like a SQL joining of two tables, I would look at this answer: Mongoose/mongoDB query joins.. but I come from a sql background

Hope that helps.

Community
  • 1
  • 1
Eric Hartmann
  • 756
  • 5
  • 12