【问题标题】:Restangular POST a Mongoose Embedded DocumentRestangular POST 一个 Mongoose 嵌入式文档
【发布时间】:2015-10-14 04:36:54
【问题描述】:

我在使用 Restangular 使用新对象 reviews 更新我的 Mongodb 数据库中的现有文档 (products) 时遇到问题。到目前为止,我可以毫无问题地向前端添加评论,但我无法将评论详细信息发布到我的数据库中。目前,当我提交新的review 时,我的代码会在我的products 集合中创建一个新密钥,但不会保存评论的详细信息。我如何将评论推送到服务器?如果我需要提供任何其他详细信息或澄清,请告诉我。任何帮助将不胜感激。

产品的 JSON 示例

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

添加评论后,这是我的新评论的 JSON 输出

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

这是我期望在 JSON 输出中看到的内容

{"__v":0,"_id":"xxxxxx","stars":4,"body":"Test review","author":"example@domain.com","createdOn":143767117903}

项目详情

我使用了 Yeoman 角度生成器,所以我有一个 server 和一个 client 目录。我正在使用MongoDBMongooseJSExpressJSAngularJSNodeJS。据我所知,我的产品的服务器路由正在运行,因为我能够查看所有产品、添加产品、查看产品(包括与产品相关的任何评论),并至少添加一个空白评论。

我有一个 products 架构,其中包含一个嵌入到 reviews 架构的文档。

产品架构

/**
* 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;

评论架构

/**
* 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;

产品评论控制器

(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){

                 });
             };
})();

产品服务

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

【问题讨论】:

    标签: angularjs mongodb restangular


    【解决方案1】:

    一位同事提供的解决方案是编辑我的产品/评论路由的服务器路由。

    更新的产品审核控制器

    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 = {};
            };
        }]);
    

    更新评论路线

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

    一旦我提交更改,我还将发布指向我的 GitHub 项目中文件的直接 URL。

    【讨论】:

      猜你喜欢
      • 2011-12-21
      • 2017-06-22
      • 1970-01-01
      • 2012-06-08
      • 2011-09-01
      • 1970-01-01
      • 2014-01-29
      • 2014-11-15
      • 2015-07-17
      相关资源
      最近更新 更多