0

我是 Mongoose 的新手,我在搜索时遇到了问题。

这些是我的架构:

var CommentSchema = new Schema({
    body       : String
  , comments   : [CommentSchema]
});

var PostSchema = new Schema({
    body        : String
  , comments    : [CommentSchema]
});

评论有很深的嵌套。当有人回答现有评论时,我怎样才能找到那个?

4

2 回答 2

0

One solution to this is to store Comments as a separate Model which you can query directly, and store references to the related ObjectIds and paths between Comments and Posts.

Using the Populate feature in Mongoose related documents can function similarly to embedded documents, although there are some important differences in the way you query them, and you have to be more careful to keep the relationships populated.

Set it up like this:

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
  , ObjectId = Schema.Types.ObjectId;

var PostsSchema = new Schema({
  body     : String,
  stories  : [{ type: ObjectId, ref: 'Story' }]
});

var CommentsSchema = new Schema({
  body     : String,
  post     : { type: ObjectId, ref: 'Post' },
  comments : [{ type: ObjectId, ref: 'Comment' }]
});

var Story   = mongoose.model('Post', PostsSchema);
var Comment = mongoose.model('Comment', CommentsSchema);

If you do it this way it requires more queries to get the post with all its comments (which will be slower than being able to load the Post and its complete comment hierarchy with a single query) however you'll be able to query comments directly and retrieve the Post they were made on (but not easily find the full path to the comment when its nested).

These are all trade-offs; the best decision (either to recursively search for comments, or store them independently then recursively load them) should be made in the context of your application and its expected usage patterns.

One other caveat; the populate feature is currently limited to a single-level of linked ObjectIds; you have to call it on each comment that is returned to get the full nested dataset. There are several plugins that help with this, such as mongoose-subpopulate, and soon enough it'll be supported natively in Mongoose - see the github issue here.

于 2012-10-16T12:51:16.613 回答
0

您可以查看 github 上的 mongoose 测试套件以获取示例。

模型查询测试

这是您要查找的内容:

基于嵌入式文档字段的测试结果:

function () {
    var db = start(), BlogPostB = db.model('BlogPostB', collection);

    BlogPostB.create({comments: [{title: 'i should be queryable'}]}, function (err, created) {
      should.strictEqual(err, null);
      BlogPostB.findOne({'comments.title': 'i should be queryable'}, function (err, found) {
        should.strictEqual(err, null);
        found._id.should.eql(created._id);
        db.close();
      });
    });
    },
于 2011-06-01T21:55:19.897 回答