把我的头靠在墙上,我知道这有点蠢......
我有一个基本评论(评论)/投票系统。我正在从mongo db和asysnc.waterfall函数中提取评论,试图将评论添加到每个评论中。这是添加投票的功能:
function(reviews, callback) {
let newReviews = [];
_.forEach(reviews, function(review,idx) {
Vote.find({review:review._id}).exec(function(err1, votes){
if (err1){
callback(err1,null);
}else{
console.log("1: REVIEW - ", review);
review.votes = votes;
console.log("2: VOTES - ", review.votes);
newReviews.push(review);
console.log("3: REVIEW - ", review);
if( newReviews.length == reviews.length ){
callback(null,newReviews);
}
}
});
});
}
即使有数据,投票项也永远不会被填充。以下是这些日志记录语句的一些输出:
1: REVIEW - { _id: 5a2086139c3c077e546622,
user:
{ passProfileImageURL: '/modules/users/client/img/profile/default.png',
_id: 5a15cd47b9fd942e50e5b,
provider: 'local',
username: 'xxx',
profileImageURL: '/modules/users/client/img/profile/default.png' },
beach:
{ _id: 57995db6666f1ec6f3750,
slug: 'carmel-city-beach-carmel-by-the-sea-california-united-states',
Name: 'Carmel City Beach' },
totalVotes: 1,
reports:
[ { _id: 5a2087f672107f48dd4ed,
user: 5a15cd47db50942e50e5b,
review: 5a208639c3c077e546622,
__v: 0,
updated: 2017-11-30T22:36:38.598Z,
created: 2017-11-30T22:36:38.598Z } ],
created: 2017-11-30T22:30:14.276Z,
comment: 'Why am i doing this???',
rating: 3 }
2: VOTES - [ { _id: 5a26fab26a6f85b39484,
review: 5a20867c3c077e546622,
Type: 'review',
user: 5a15cd4db50942e50e5b,
__v: 0,
updated: 2017-12-05T19:59:46.318Z,
created: 2017-12-05T19:59:46.318Z,
IsVote: true } ]
3: REVIEW - { _id: 5a208676139c3c077e546622,
user:
{ passProfileImageURL: '/modules/users/client/img/profile/default.png',
_id: 5a15cd47b50942e50e5b,
provider: 'local',
username: 'mit',
profileImageURL: '/modules/users/client/img/profile/default.png' },
beach:
{ _id: 579db6666fcec6f3750,
slug: 'carmel-city',
Name: 'Carmel City' },
totalVotes: 1,
reports:
[ { _id: 5a2087b107f48dd4ed,
user: 5a15cfdb50942e50e5b,
review: 5a208673c077e546622,
__v: 0,
updated: 2017-11-30T22:36:38.598Z,
created: 2017-11-30T22:36:38.598Z } ],
created: 2017-11-30T22:30:14.276Z,
comment: 'Why am i doing this???',
rating: 3 }
没有意义的是,数字2项会正确记录,但3没有...任何人都可以帮我理解这个愚蠢的问题吗?还是只是我? LOL
根据要求,这是投票mongoose架构定义:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var config = {
Type: {
type: String
},
IsVote: {
type: Boolean,
default: true
},
created: {
type: Date,
default: Date.now
},
updated: {
type: Date,
default: Date.now
},
owner: {
type: Schema.ObjectId
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
review: {
type: Schema.ObjectId,
ref: 'Review'
}
};
var VoteSchema = new Schema(config, {
collection: 'votes'
});
/**
* Hook a pre save method to hash the password
*/
VoteSchema.pre('save', function(next) {
next();
});
VoteSchema.method('toggleVote', function() {
this.IsVote = !this.IsVote;
return this.save();
});
VoteSchema.static('createFromReview', function(reviewId, user) {
return new this({
review: reviewId,
Type: 'review',
user: user
});
});
mongoose.model('Vote', VoteSchema);