查询Mongoose Schema。嵌套的注释数组

时间:2015-09-11 18:13:13

标签: node.js mongodb mongoose

我有场地,每个场地都有评论部分。每条评论都是一个Mongoose评论架构。每个评论都有一个创建者属性,它是一个用户模式。我试图查找特定用户发布的所有评论。我怎样才能做到这一点?

var VenueSchema = new mongoose.Schema({
  comments: [{
    type : mongoose.Schema.Types.ObjectId,
    ref: 'Comment',
    default: []
  }]
},
{minimize: false});

var CommentSchema = new mongoose.Schema({
  creator: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
}, {minimize: false});


var UserSchema = new mongoose.Schema({
  token: String,
  venues: [{ //in case we want users to save their favorite venues
    type : mongoose.Schema.Types.ObjectId,
    ref: 'Venue'
  }]
});

我试过了

Venue.find({
    "comments.creator":  "55f1fa1263877ed0067b78c0"
  }, function(err, docs) {
    console.log(docs);
    res.send(docs);
  })

但它返回一个空数组。 " 55f1fa1263877ed0067b78c0"是一个样本创建者_id。提前谢谢!

2 个答案:

答案 0 :(得分:0)

您无法通过creater集合中的ID搜索Venue因为它仅收集Comment ID。因此,要按其ID搜索creater,您需要更改如下:

var VenueSchema = new mongoose.Schema({
  comments: [CommentSchema]
},
{minimize: false});

var CommentSchema = new mongoose.Schema({
  creator: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
}, {minimize: false});


var UserSchema = new mongoose.Schema({
  token: String,
  venues: [{ //in case we want users to save their favorite venues
    type : mongoose.Schema.Types.ObjectId,
    ref: 'Venue'
  }]
});

答案 1 :(得分:0)

由于venueSchema仅存储引用注释(可以是注释_id),因此您将无法使用场地模型查询注释。您可以将注释文档嵌入到场地模式的注释数组中。

只需使用评论模型查询评论集合,如下所示

Comment.find({
    "creator":  "55f1fa1263877ed0067b78c0"
  }, function(err, docs) {
    console.log(docs);
    res.send(docs);
  })