Herr Josua
Herr Josua

Reputation: 453

Restangular POST a Mongoose Embedded Document

I am having trouble using Restangular to update an existing document (products) within my Mongodb database with a new object reviews. So far I am able to add a review to the front-end with no issues, but I am having trouble posting the review details to my database. Currently when I submit a new review my code creates a new key within my products collection, but does not save the details of the review. How would I push the review to the server? Please let me know if I need to provide any additional details, or clarifications. Any help will be greatly appreciated.

Sample JSON of a product

{"_id":"xxxxx","name":"Product 1","description":"Product 1 Description","price":"1299.99","createdOn":"143767117903", "reviews":[{}]}

After adding a review this what my JSON output of my new review

{"__v":0,"_id":"xxxxxx"}

This is what I am expecting to see within my JSON output

{"__v":0,"_id":"xxxxxx","stars":4,"body":"Test review","author":"[email protected]","createdOn":143767117903}

Project details

I used the Yeoman angular generator so I have a server and a client directories. I am using MongoDB, MongooseJS,ExpressJS, AngularJS, and NodeJS. As far as I know my server routes for my products are working as I am able to view all products, add a product, view a product (include any reviews associated with the product), and at least add a blank review.

I have a products schema that includes an Embedded Document to a reviews schema.

Products Schema

/**
* Schema for Products
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var productSchema = new Schema({
    name: {
        type: String,
        require: true,
    },
    description: {
        type: String,
        require: true,
    },
    shine: {
        type: Number,
        require: true,
    },
    price: {
        type: Number,
        require: true,
    },
    rarity: {
        type: Number,
        require: true,
    },
    color: {
        type: String,
        require: true,
    },
    faces: {
        type: Number,
        require: true,
    },
    images: {},
    reviews: [{type: mongoose.Schema.Types.ObjectId, ref: 'Review'}],
    createdOn: {
        type: Date
    }
});
var Product = mongoose.model('Product', productSchema);
module.exports = Product;

Reviews schema

/**
* Schema for Product Reviews
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var reviewSchema = new Schema({
    stars: {
        type: Number
    },
    review: {
        type: String
    },
    author: {
        type: String
    },
    createdOn: {
        type: Date
    }
});
var Review = mongoose.model('Review', reviewSchema);
module.exports = Review;

Products Reviews Controller

(function() {
    'use strict';
    /**
    * @ngdoc function
    * @name gemStoreApp.controller:ReviewCtrl
    * @description
    * # ReviewCtrl
    * Controller of the gemStoreApp
    */
    angular.module('gemStoreApp')
        .controller("ReviewCtrl", ['$scope', 'Restangular', 'productsService', function ($scope, Restangular, productsService) {
             this.review();

             this.addReview = function(product){
                 this.review.createdOn = Date.now();

                 var productReview = Restangular.all('/products/' + product._id + '/reviews');

                 productReview.post(product).then(function(newResource){

                 });
             };
})();

Products Service

(function() {
    'use strict';
    /**
    * @ngdoc service
    * @name gemStoreApp.productService
    * @description
    * # productService
    */
    angular.module('gemStoreApp.productService',['ngResource'])
        .factory('productsService', function($resource) {
            return $resource('/products/:id', {id:'@id'},{
                'update': { method: 'PUT'}
            });
        });
    })(); 

Upvotes: 0

Views: 165

Answers (1)

Herr Josua
Herr Josua

Reputation: 453

The solution which was provided by a co-worker is to edit the server routes for my product/reviews routed.

updated products review controller

angular.module('gemStoreApp')
    .controller('ReviewCtrl', ["$scope, ,'$resource', '$Restangular', 'productsService', function ($scope, $resource, Restangular, productsService) {
        this.review = {};

        this.addReview = function(product){
            this.review.createdOn = Date.now();
            var productReview = Restangular.all('/products/' + product._id + '/reviews');
            var updatedProduct = product;
            productReview.post(this.review).then(function(newResource){
                product.reviews.push(newResource);
            });

            this.review = {};
        };
    }]);

updated reviews route

...
router.post('/:product/reviews', function (req, res, next) {
    var time = moment().formated('MMMM Do YYYY, h:mm:ss a');
    var body = req.review;

    var review = new Review(req.body);
    review.product = req.product

    review.save(function (err, review){
      if (err) {return next(err);}

     req.product.reviews.push(review);

     req.products.save(function (err, product) {
         if (err) {return next(err);}

         res.json(review);
         res.status(201).json({
           'message': review.review + 'created'
         });
    });
});
...

I will also post the direct URL to the files on my GitHub project once I commit my changes.

Upvotes: 1

Related Questions