使用mongoose返回特定用户的所有注释,而不包含其他文档字段 [英] returning all comments by a specific user without other document fields using mongoose
本文介绍了使用mongoose返回特定用户的所有注释,而不包含其他文档字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var mongoose = require('mongoose');
// defines the database schema for this object
var schema = mongoose.Schema({
projectName : String,
authorName : String
comment : [{
id : String,
authorName : String,
authorEmailAddress : { type : String, index : true }
}]
});
})
// Sets the schema for model
var ProjectModel = mongoose.model('Project', schema);
// Create a project
exports.create = function (projectJSON) {
var project = new ProjectModel({
projectName : projectJSON.projectName ,
authorName : projectJSON.authorName,
comment : [{
id : projectJSON.comments.id,
authorName : projectJSON.comments.authorName,
authorEmailAddress : projectJSON.authorEmailAddress
});
project.save(function(err) {
if (err) {
console.log(err);
}
else{
console.log("success");
}
});
}
问:我想检索所有项目中的特定用户的所有评论(没有其他文档字段)
我的尝试:
// assuming email address is unique per user, as user can always change displayName for instance
exports.allCommentsByUser = function(userEmail, callback){
ProjectModel.find(
{"comments.authorEmailAddress" : userEmail},
{ "projectName" : 1, "comments.authorEmailAddress" : 1 },
callback);
};
推荐答案
您可以将2.2聚合框架用于此类型的查询:
You can use the 2.2 aggregation framework for this type of query:
ProjectModel.aggregate([
{
// Only include the projectName and comments fields.
$project: { 'projectName': true, 'comments': true, '_id': false }
}, {
// Get all project docs that contain comments by this user
$match: { 'comments.authorEmailAddress': userEmail }
}, {
// Duplicate the project docs, one per comment.
$unwind: '$comments'
}, {
// Filter that result to just the comments by this user
$match: { 'comments.authorEmailAddress': userEmail }
}], callback
);
这篇关于使用mongoose返回特定用户的所有注释,而不包含其他文档字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文