聚合函数上复制页面刷新在NG-重复项目。需要弄清楚如何停止重复。 Angularjs MongoDB的猫鼬弄清楚、函数、页面、项目

2023-09-14 23:06:15 作者:他对你的温柔疼爱,学不来

我有一个集合中的项目通过这个总运行平均得分找到他们,找到他们时,他们还没有评论/额定呢。

I have items in a collection that run through this aggregate to find them with an average rating and to find them when they have not yet been commented on / rated yet.

它的工作原理,但每次我现在刷新页面,它使一个重复的波旁集合中的每个项目的NG-重复内显示。项目的波旁集合中的实际金额并没有改变。我该如何停止?服务器端:波旁模式:

It works, but everytime I refresh the page now, it makes a duplicate on display within the ng-repeat of each item in the bourbon collection. The actual amount of items in the bourbon collection is not changing. How do I stop this? SERVER SIDE: bourbon schema:

'use strict';

var mongoose = require('mongoose'),
    BourbonSchema = null;

module.exports = mongoose.model('Bourbon', {
    name:  {type: String, required: true},
    blog:  {type: String, required: true},
    photo: {type: String, required: true, default:'http://aries-wineny.com/wp-content/uploads/2014/09/woodford-reserve.jpg'},
    location: {type: String, required: true},
    distillery: {type: String, required: true},
    comments: [{type: mongoose.Schema.ObjectId, ref: 'Comments'}],
    rating : {type: Number}
});

var Bourbon = mongoose.model('Bourbon', BourbonSchema);
module.exports = Bourbon;

评论/评价模式:

comment/rating schema:

'use strict';

var mongoose = require('mongoose');

module.exports = mongoose.model('Comment', {
    bourbonId:   {type: mongoose.Schema.ObjectId, ref: 'Bourbon'},
    userId:   {type: mongoose.Schema.ObjectId, ref: 'User'},
    text:     {type: String, required: true},
    createdAt: {type: Date,  required: true, default: Date.now},
    rating  : {type: Number, required: true},
    votes:     {type: Number, default: 0}
});

聚合函数:

'use strict';

var Bourbon = require('../../../models/bourbon'),
    Comment = require('../../../models/comment'),
    DataStore = require('nedb'),
    db = new DataStore(),
    async = require('async');

module.exports = {
    description: 'Get Bourbons',
    notes: 'Get Bourbons',
    tags: ['bourbons'],
    handler: function(request, reply){

        async.series(
            [
                function(callback){
                    Bourbon.find({},function(err,results){
                        //if (err) callback(err);
                        async.eachLimit(results,10,function(result,callback){
                            var plain = result.toObject();
                            plain.bourbonId = plain._id.toString();
                            plain.avgRating = 0;
                            delete plain._id;

                            db.insert(plain,callback);
                        },callback);
                    });
                },

                function(callback){
                    Comment.aggregate(
                        [
                            {$group:{
                                _id: '$bourbonId',
                                avgRating:{$avg:'$rating'}
                            }}
                        ],
                        function(err,results){
                            async.eachLimit(results,10,function(result,callback){
                                db.update(
                                    {bourbonId: result._id.toString()},
                                    {$set: {avgRating: result.avgRating}},
                                    callback                   
                                );
                            },callback);                 
                        }
                    );
                }
            ],

            function(err){
                //if (err) callback(err);
                db.find({}, {_id: 0}, function(err, bourbons){
                    console.log('DOOOOCS', bourbons);
                    reply ({bourbons:bourbons});
                });
            });
    }
};

客户端

factory:

(function(){
    'use strict';

    angular.module('hapi-auth')
        .factory('Bourbon', ['$http', function($http){

            function create(bourbon){
                return $http.post('/admin', bourbon);
            }

            function all(){
                return $http.get('/admin');
            }

            return {create:create, all:all};
        }]);
})();

控制器:

(function(){
    'use strict';

    angular.module('hapi-auth')
        .controller('AdminCtrl', ['$scope', 'Bourbon', function($scope, Bourbon){
            //$scope.blog.photo = [];
            $scope.bourbon = {};
            $scope.bourbons = [];

            Bourbon.all().then(function(res){
                $scope.bourbons = res.data.bourbons;
                console.log(res.data.bourbons);
            });

            $scope.createBourbon = function(bourbon){
                console.log('BOURBB', bourbon);
                Bourbon.create(bourbon).then(function(res){
                    console.log('bourboonnnn', res.data);
                    $scope.bourbons.push(res.data);

                });
            };


        }]);
})();

玉:

.row
   .small-4.columns
   .small-4.columns
      .review
         .insertContainer(ng-repeat='bourbon in bourbons')
            .adminName Name: {{bourbon.name}}
            img.bourbonImg(src='{{bourbon.photo}}')
            .adminBlog {{bourbon.blog.slice(0,200)}} ...
   .small-4.columns

试图阻止对页面刷新波旁集合中的项目重复....不知道如果我需要实现某种这里更换方法..现在有点卡住。

trying to stop duplication of items in bourbon collection on page refresh.... Not sure if I need to implement some sort of replace method here.. a bit stuck now..

这是什么控制台登录控制器/聚合函数返回:

This is what the console log in the controller / aggregate function returns:

DOOOOCS [ { name: 'woodford reserve',
    location: 'kentucky',
    distillery: 'woodford',
    blog: 'fjkd;asdljfkld;ksdfj',
    __v: 0,
    comments: [],
    photo: 'http://aries-wineny.com/wp-content/uploads/2014/09/woodford-reserve.jpg',
    bourbonId: '54c2aa5556267e0000b5618c',
    avgRating: 0 },
  { name: 'woodford reserve',
    location: 'kentucky',
    distillery: 'woodford',
    blog: 'fjkd;asdljfkld;ksdfj',
    __v: 0,
    comments: [],
    photo: 'http://aries-wineny.com/wp-content/uploads/2014/09/woodford-reserve.jpg',
    bourbonId: '54c2aa5556267e0000b5618c',
    avgRating: 0 } ]

似乎每当这个功能是运行...,它运行在页面刷新的角度控制器内的Bourbon.all复制波旁王朝集合中的每个项目。

it seems to duplicate each item in the Bourbons collection whenever this function is run... , which it runs on page refresh as the Bourbon.all within the angular controller.

这是集合中的波本威士忌,它贯穿于前总:

this is the bourbon in the collection, before it runs through the aggregate:

{
    "_id" : ObjectId("54c2aa5556267e0000b5618c"),
    "name" : "woodford reserve",
    "location" : "kentucky",
    "distillery" : "woodford",
    "blog" : "fjkd;asdljfkld;ksdfj",
    "comments" : [],
    "photo" : "https://m.xsw88.com/allimgs/daicuo/20230914/10.png.jpg",
    "__v" : 0
}

更新玉W /按部就班地进行:

updated jade w/ track by:

.row
   .small-4.columns
   .small-4.columns
      .review
      .insertContainer(ng-repeat='bourbon in bourbons | unique: bourbon.bourbonId | filter: query')

            .adminName Name: {{bourbon.name}}
            img.bourbonImg(src='{{bourbon.photo}}')
            .adminBlog {{bourbon.blog.slice(0,200)}} ...
   .small-4.columns

这使得项目上显示的第一个负载,但在任何刷新/重载,现在我得到这个错误:

this allows the items to show on the first load, but on any refresh / reload, I now get this error:

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: bourbon in bourbons track by bourbon.bourbonId | filter:query, Duplicate key: 54c2aa5556267e0000b5618c, Duplicate value: {"name":"woodford reserve","location":"kentucky","distillery":"woodford","blog":"fjkd;asdljfkld;ksdfj","__v":0,"comments":[],"photo":"https://m.xsw88.com/allimgs/daicuo/20230914/10.png.jpg","bourbonId":"54c2aa5556267e0000b5618c","avgRating":0}
http://errors.angularjs.org/1.3.8/ngRepeat/dupes?p0=bourbon%20in%20bourbons…C%22bourbonId%22%3A%2254c2aa5556267e0000b5618c%22%2C%22avgRating%22%3A0%7D
    at http://localhost:7070/vendor/angular/angular.js:63:12
    at ngRepeatAction (http://localhost:7070/vendor/angular/angular.js:24483:21)
    at Object.$watchCollectionAction [as fn] (http://localhost:7070/vendor/angular/angular.js:14092:13)
    at Scope.$digest (http://localhost:7070/vendor/angular/angular.js:14225:29)
    at Scope.$apply (http://localhost:7070/vendor/angular/angular.js:14488:24)
    at done (http://localhost:7070/vendor/angular/angular.js:9646:47)
    at completeRequest (http://localhost:7070/vendor/angular/angular.js:9836:7)
    at XMLHttpRequest.requestLoaded (http://localhost:7070/vendor/angular/angular.js:9777:9)

这些都是在浏览器控制台返回的波本威士忌的项目。他们都具有相同的bourbonId,从索引0独特的过滤现在回到2波本威士忌的对象,而不是所有的人......(原件及副本之一):

these are the bourbon items being returned in the browser console. all of them have the same bourbonId, starting with index 0. Unique filter is returning 2 bourbon objects now, (the original and one of the duplicates?) instead of all of them... :

[对象,对象,目标,对象,对象] 0:对象$$ hashKey:对象:6五:0avgRating:4blog:fjkd; asdljfkld; ksdfjbourbonId:54c2aa5556267e0000b5618c评论:数组[0]酒厂:伍德福德的位置:肯德基的名字:伍德福德储备照片的http://aries-wineny.com/wp-content/uploads/2014/09/woodford-reserve.jpg\"__proto: Object1:Object__v:0avgRating:4blog:fjkd; asdljfkld; ksdfjbourbonId:54c2aa5556267e0000b5618c评论:数组[0]酒厂:伍德福德的位置:肯德基的名字:伍德福德储备照片的http://aries-wineny.com/wp-content/uploads/2014/09/woodford-reserve.jpg\"proto: Object2的:对象$$ hashKey:对象:7五:0avgRating:0blog:fjkd; asdljfkld; ksdfjbourbonId:54c2aa5556267e0000b5618c评论:数组[0]长度:0__proto :数组[0 ]酒厂:伍德福德的位置:肯德基的名字:伍德福德储备照片的http://aries-wineny.com/wp-content/uploads/2014/09/woodford-reserve.jpg\"proto: Object3:Object__v:0avgRating:0blog:fjkd; asdljfkld; ksdfjbourbonId:54c2aa5556267e0000b5618c评论:数组[0]长度:0__proto__:数组[0]酒厂:伍德福德的位置:肯德基的名字:伍德福德储备照片:的http://aries-wineny.com/wp-content/uploads/2014/09/woodford-reserve.jpg\"proto: Object4:Object__v:0avgRating:0blog:fjkd; asdljfkld; ksdfjbourbonId:54c2aa5556267e0000b5618c评论:数组[0]长度:0__proto__:数组[0]酒厂:伍德福德的位置:肯德基的名字:伍德福德储备照片:的http://aries-wineny.com/wp-content/uploads/2014/09/woodford-reserve.jpg\"proto: Objectlength:5__proto__:数组[0]

[Object, Object, Object, Object, Object]0: Object$$hashKey: "object:6"v: 0avgRating: 4blog: "fjkd;asdljfkld;ksdfj"bourbonId: "54c2aa5556267e0000b5618c"comments: Array[0]distillery: "woodford"location: "kentucky"name: "woodford reserve"photo: "https://m.xsw88.com/allimgs/daicuo/20230914/10.png.jpg"__proto: Object1: Object__v: 0avgRating: 4blog: "fjkd;asdljfkld;ksdfj"bourbonId: "54c2aa5556267e0000b5618c"comments: Array[0]distillery: "woodford"location: "kentucky"name: "woodford reserve"photo: "https://m.xsw88.com/allimgs/daicuo/20230914/10.png.jpg"proto: Object2: Object$$hashKey: "object:7"v: 0avgRating: 0blog: "fjkd;asdljfkld;ksdfj"bourbonId: "54c2aa5556267e0000b5618c"comments: Array[0]length: 0__proto: Array[0]distillery: "woodford"location: "kentucky"name: "woodford reserve"photo: "https://m.xsw88.com/allimgs/daicuo/20230914/10.png.jpg"proto: Object3: Object__v: 0avgRating: 0blog: "fjkd;asdljfkld;ksdfj"bourbonId: "54c2aa5556267e0000b5618c"comments: Array[0]length: 0__proto__: Array[0]distillery: "woodford"location: "kentucky"name: "woodford reserve"photo: "https://m.xsw88.com/allimgs/daicuo/20230914/10.png.jpg"proto: Object4: Object__v: 0avgRating: 0blog: "fjkd;asdljfkld;ksdfj"bourbonId: "54c2aa5556267e0000b5618c"comments: Array[0]length: 0__proto__: Array[0]distillery: "woodford"location: "kentucky"name: "woodford reserve"photo: "https://m.xsw88.com/allimgs/daicuo/20230914/10.png.jpg"proto: Objectlength: 5__proto__: Array[0]

我想我已经收窄这是在服务器端的问题,上面列出的控制器/聚集内。我需要找到一种方法来代替,而不是创建一个新的每次Bourbon.all被调用时/在客户端/浏览器中运行...现在试图解决这一问题的更新文件。任何提示,多AP preciated。

I think I've narrowed this to being an issue on the server side, within the controller / aggregate listed above. I need to find a way to replace the updated documents, instead of creating a new one each time the Bourbon.all is called / run on the client side / browser ... trying to tackle it now. Any tips, much appreciated.

推荐答案

这似乎只是走一个例子,望文生义的情况。你对每个请求的双重输出结束了,因为那是多么的地方,结果都来自卖场的作用域。

This seems to be just a case of taking an example too literally. You're ending up with duplicated output on each request because that is how the store where the results are coming from is scoped.

因此​​,而不是这样的:

So instead of this:

'use strict';

var Bourbon = require('../../../models/bourbon'),
    Comment = require('../../../models/comment'),
    DataStore = require('nedb'),
    db = new DataStore(),          // <-- globally scoped in the module :(
    async = require('async');

module.exports = {
    description: 'Get Bourbons',
    notes: 'Get Bourbons',
    tags: ['bourbons'],
    handler: function(request, reply){

        async.series(
            [
                function(callback){

而做到这一点:

'use strict';

var Bourbon = require('../../../models/bourbon'),
    Comment = require('../../../models/comment'),
    DataStore = require('nedb'),
    async = require('async');

module.exports = {
    description: 'Get Bourbons',
    notes: 'Get Bourbons',
    tags: ['bourbons'],
    handler: function(request, reply){

        db = new DataStore();   // <--- Init store within request scope :)

        async.series(
            [
                function(callback){
 
精彩推荐
图片推荐