Javascript 使用mongoose返回特定用户的所有注释,而不返回其他文档字段
Javascript 使用mongoose返回特定用户的所有注释,而不返回其他文档字段,javascript,mongodb,indexing,mongoose,Javascript,Mongodb,Indexing,Mongoose,}) Q:我想检索特定用户在所有项目中发表的所有评论(没有其他文档字段) 我的尝试: // Sets the schema for model var ProjectModel = mongoose.model('Project', schema); // Create a project exports.create = function (projectJSON) { var project = new ProjectModel({ projectName : projec
})
Q:我想检索特定用户在所有项目中发表的所有评论(没有其他文档字段)
我的尝试:
// 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");
}
});
}
您可以将2.2聚合框架用于此类查询:
// 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聚合框架用于此类查询:
// 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);
};
看起来应该有用,你试过了吗?当你运行代码的时候会发生什么?看起来应该可以,你试过了吗?运行代码时会发生什么情况?这是最好的方法,因为$positional操作符只返回匹配的嵌入文档数组的第一个元素。在哪里使用此查询?在架构中,或作为
导出.allCommentsByUser
函数的一部分?allCommentsByUser
中的@bouncingHippo代替查找
。谢谢,与查找()相反,使用聚合是否有什么缺点?
@bouncingHippo聚合
通常比查找慢,因此,只在需要时使用它。这是最好的方法,因为$positional操作符只返回嵌入文档匹配数组的第一个元素。我在哪里使用此查询?在架构中,或作为导出.allCommentsByUser
函数的一部分?allCommentsByUser
中的@bouncingHippo代替查找
。谢谢,与查找()相反,使用聚合是否有什么缺点?
@bouncingHippo聚合
通常比查找慢,所以只在你需要的时候使用它。
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
);