【发布时间】: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 目录。我正在使用MongoDB、MongooseJS、ExpressJS、AngularJS 和 NodeJS。据我所知,我的产品的服务器路由正在运行,因为我能够查看所有产品、添加产品、查看产品(包括与产品相关的任何评论),并至少添加一个空白评论。
我有一个 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