【问题标题】:returning all comments by a specific user without other document fields using mongoose使用猫鼬返回特定用户的所有评论而没有其他文档字段
【发布时间】:2012-10-27 17:44:25
【问题描述】:
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");
    }
  });


}

问:我想检索特定用户在所有项目中创建的所有 cmets(不包括其他文档字段)

我的尝试:

// 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);
};

【问题讨论】:

  • 这看起来应该可以了,你试过了吗?运行代码时会发生什么?

标签: javascript mongodb indexing mongoose


【解决方案1】:

这种类型的查询可以使用2.2聚合框架:

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
);

【讨论】:

  • 这是最好的方法,因为 $positional 运算符只返回匹配的嵌入文档数组的第一个元素。
  • 我在哪里使用这个查询?在架构中,还是作为exports.allCommentsByUser 函数的一部分?
  • @bouncingHippo 在allCommentsByUser,代替find
  • 谢谢,使用聚合而不是find()
  • @bouncingHippo aggregate 一般比find 慢,所以只在需要时使用。
猜你喜欢
  • 2021-05-11
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
  • 2022-09-24
  • 1970-01-01
  • 2023-03-20
  • 2018-11-06
相关资源
最近更新 更多