我有一个基本系统,用户可以阻止其他用户或故事。
目标是当用户阻止其他用户时,它不会显示被阻止用户创建的故事但被阻止的元素是故事,然后可以看到其他故事,但不会被阻止。
下面我粘贴所有正在进行工作的代码:
userModel.js
var UserSchema = new mongoose.Schema({
// Some other info stuff
block: [{
_id: false,
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
story: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Story'
},
ts: {
type: Date,
default: Date.now
}
}]
}, { timestamps: { createdAt: 'created_at' } });
UserSchema.statics.getBlocked = function (user_id) {
return this.findById(user_id)
.select('block.user block.story')
.exec();
};
module.exports = mongoose.model('User', UserSchema);
storyModel.js
var StorySchema = new mongoose.Schema({
title: {
type: String,
trim: true
},
anonymous: {
type: Boolean,
default: false
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
// More stuff
}, { timestamps: { createdAt: 'created_at' } });
StorySchema.methods = {
filterAnonymousStory: function () {
var data = this;
return new Promise(function (resolve, reject) {
if (data.anonymous === true) {
data.user = undefined;
}
data.anonymous = undefined;
resolve(data);
});
},
filterBlocked: function (blocked) {
var data = this, i;
return new Promise(function (resolve, reject) {
if (!blocked.block) {
resolve(data);
} else {
for (i = 0; i < blocked.block.length; i += 1) {
if (typeof blocked.block[i].user !== "undefined" && JSON.stringify(blocked.block[i].user) === JSON.stringify(data.user._id)) {
data = undefined;
} else if (typeof blocked.block[i].story !== "undefined" && JSON.stringify(blocked.block[i].story) === JSON.stringify(data._id)) {
data = undefined;
}
}
resolve(data);
}
});
}
};
StorySchema.statics.getAllStories = function (blocked) {
var i, promise = [];
return this.find()
.select('_id anonymous title user')
.populate({
path: 'user',
select: '_id',
model: 'User'
})
.sort('-created_at')
.limit(200)
.exec()
.then(function (data) {
var blockedPromises = [], anonymousPromises = [], i;
if (!data) {
throw new Error('There aren\'t stories');
}
for (i = 0; i < data.length; i += 1) {
blockedPromises.push(data[i].filterBlocked(blocked));
}
return Promise.all(blockedPromises)
.then(function (data) {
for (i = 0; i < data.length; i += 1) {
if (data[i]) {
anonymousPromises.push(data[i].filterAnonymousStory());
} else {
return Promise.resolve(data);
}
}
return Promise.all(anonymousPromises);
});
});
};
所以我的问题是,如果有另一种方式比我做的更好或更容易做到这一点。
同样,我打开了提示&amp;建议,因为我对node
&amp; mongoDB