1
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");
    }
  });


}

Q: 特定のユーザーがすべてのプロジェクトで作成したすべてのコメント (他のドキュメント フィールドを除く) を取得したいと考えています。

私の試み:

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

1 に答える 1

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
);
于 2012-11-07T16:48:53.447 に答える