English 中文(简体)
搜索嵌入文档Mongoose+nodejs
原标题:Searching embedded documents Mongoose + nodejs

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

以下是我的示意图:

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

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

评论嵌套很深。当有人回答现有的评论时,我如何才能找到它?

问题回答

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

模型_查询_测试

以下是您要查找的内容:

基于嵌入式文档字段的测试查找:

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();
      });
    });
    },

对此的一个解决方案是将Comments存储为一个单独的模型,您可以直接查询该模型,并存储对相关ObjectId的引用以及Comments和Posts之间的路径。

使用Mongoose相关文档中的填充功能可以与嵌入文档类似,尽管在查询它们的方式上存在一些重要差异,并且必须更加小心地填充关系。

设置如下:

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

如果你这样做,它需要更多的查询才能获得包含所有评论的帖子(这比用一个查询加载帖子及其完整的评论层次结构要慢),但是你可以直接查询评论并检索他们发表的帖子(但在嵌套评论时不容易找到评论的完整路径)。

这些都是权衡;最好的决定(要么递归地搜索注释,要么独立存储注释,然后递归地加载注释)应该在应用程序及其预期使用模式的上下文中做出。

另一个警告;填充特征当前被限制为链接的ObjectId的单个级别;您必须在返回的每个注释上调用它才能获得完整的嵌套数据集。有几个插件可以帮助实现这一点,例如猫鼬子种群,很快它将在mongoose中得到本地支持-请参阅此处出现github问题





相关问题
Access DB Ref MongoDB

Whats the best way to access/query a DB Ref: UPDATE: users: name, groupref : {$ref:"groups",$id:"ObjectId ..." } } groups: name, topic, country,...,.. Assumption is that user belongs to only one ...

MongoDB nested sets

What re the best practices to store nested sets (like trees of comments) in MongoDB? I mean, every comment can have a parent comment and children-comments (answers). Storing them like this: { ...

MongoMapper and migrations

I m building a Rails application using MongoDB as the back-end and MongoMapper as the ORM tool. Suppose in version 1, I define the following model: class SomeModel include MongoMapper::Document ...

MongoDB takes long for indexing

I have the following setup: Mac Pro with 2 GB of RAM (yes, not that much) MongoDB 1.1.3 64-bit 8 million entries in a single collection index for one field (integer) wanted Calling .ensureIndex(...) ...

Storing and accessing large amounts of data

My application creates pieces of data that, in xml, would look like this: <resource url="someurl"> <term> <name>somename</name> <frequency>somenumber</...

热门标签