Mongoose:populate方法不能正常工作

时间:2021-07-10 13:20:39

I could use some help here, I can't figure out why the populate method doesn't work as expected. I want to model some "rooms" with people inside them.

我可以在这里使用一些帮助,我无法弄清楚为什么populate方法不能按预期工作。我想用里面的人模拟一些“房间”。

var PersonSchema = new Schema({
    _id   : Schema.ObjectId,
    name  : String,
});
var Person = mongoose.model('Person', PersonSchema, 'Person');

var RoomSchema = new Schema({
      _id    : Schema.ObjectId, 
      name : String,
      People : [{ type: Schema.ObjectId, ref: 'Person' }],
});
var Room = mongoose.model('Room', RoomSchema, 'Room');

So, I have a Person collection with one entry:

所以,我有一个Person集合,其中包含一个条目:

{ 
"name" : "person1", 
"_id" : ObjectId("4f9e5bb68bcd69fb0c000002") 
}

and a Room collection with one entry:

和一个入口的房间集合:

{ 
"_id" : ObjectId("4f9e5bb68bcd69fb0c000001"), 
"name" : "room1", 
"People" : [ ObjectId("4f9e5bb68bcd69fb0c000002") ] 
}

When I try to execute this query:

当我尝试执行此查询时:

Room.findOne({ 'name': 'room1' }).populate('People').run(function (err, result) {
  if(err) console.log(err);
  console.log(result);
});

I get as output:

我得到输出:

{ _id: 4f9e5bb68bcd69fb0c000001,
  name: 'room1',
  People: []
}

Why doesn't Mongoose populate the people field? I just don't understand what could be wrong.

为什么Mongoose不填充人民领域?我只是不明白什么是错的。

2 个解决方案

#1


2  

This problem was a bug in 2.x version of mongoose. It has been fixed: https://github.com/LearnBoost/mongoose/issues/877

这个问题是2.x版本的mongoose中的一个错误。它已修复:https://github.com/LearnBoost/mongoose/issues/877

#2


1  

Because mongoose doesn't 'join' data (which is what I think you're trying to do).

因为猫鼬没有'加入'数据(这是我认为你想要做的)。

What you want to do is something like this (note this is with Comments and blogpost)

你想做的是这样的事情(注意这是评论和博客)

Schema

架构

var Comments = new Schema({
    title     : String
  , body      : String
  , date      : Date
});

var BlogPost = new Schema({
    author    : ObjectId
  , title     : String
  , body      : String
  , buf       : Buffer
  , date      : Date
  , comments  : [Comments]
  , meta      : {
      votes : Number
    , favs  : Number
  }
});

Then create a blog model and set the comments (person in a room in your example)

然后创建一个博客模型并设置评论(示例中的房间中的人)

// retrieve my model
var BlogPost = mongoose.model('BlogPost');

// create a blog post
var post = new BlogPost();

// create a comment
post.comments.push({ title: 'My comment' });

post.save(function (err) {
  if (!err) console.log('Success!');
});

If you dont want to do the embedded documents, you can do a search from that callback. For example, this is my coffee-script example of exactly this getting user name from a tweets author:

如果您不想执行嵌入式文档,可以从该回调中进行搜索。例如,这是我的咖啡脚本示例,正是这个从推文作者获取用户名:

ModelTweets.find {}, (err, tweetResults) ->
    if tweetResults.length == 0
      res.render 'tweets/index', tweets: 0
    else
      # Get the Author for each tweet
      tweetResults.forEach (tweetInfo) ->
        count++
        ModelUser.findOne {'_id': tweetInfo.author}, (err, userInfo) ->
          tweets.push {id: tweetInfo._id, tweet: tweetInfo.tweet, created_at: tweetInfo.created_at, author: userInfo.username}

        if count == tweetResults.length
          res.render 'tweets/index', {tweets: tweets || {}}

That should get you on the right track :)

这应该让你走上正确的轨道:)

#1


2  

This problem was a bug in 2.x version of mongoose. It has been fixed: https://github.com/LearnBoost/mongoose/issues/877

这个问题是2.x版本的mongoose中的一个错误。它已修复:https://github.com/LearnBoost/mongoose/issues/877

#2


1  

Because mongoose doesn't 'join' data (which is what I think you're trying to do).

因为猫鼬没有'加入'数据(这是我认为你想要做的)。

What you want to do is something like this (note this is with Comments and blogpost)

你想做的是这样的事情(注意这是评论和博客)

Schema

架构

var Comments = new Schema({
    title     : String
  , body      : String
  , date      : Date
});

var BlogPost = new Schema({
    author    : ObjectId
  , title     : String
  , body      : String
  , buf       : Buffer
  , date      : Date
  , comments  : [Comments]
  , meta      : {
      votes : Number
    , favs  : Number
  }
});

Then create a blog model and set the comments (person in a room in your example)

然后创建一个博客模型并设置评论(示例中的房间中的人)

// retrieve my model
var BlogPost = mongoose.model('BlogPost');

// create a blog post
var post = new BlogPost();

// create a comment
post.comments.push({ title: 'My comment' });

post.save(function (err) {
  if (!err) console.log('Success!');
});

If you dont want to do the embedded documents, you can do a search from that callback. For example, this is my coffee-script example of exactly this getting user name from a tweets author:

如果您不想执行嵌入式文档,可以从该回调中进行搜索。例如,这是我的咖啡脚本示例,正是这个从推文作者获取用户名:

ModelTweets.find {}, (err, tweetResults) ->
    if tweetResults.length == 0
      res.render 'tweets/index', tweets: 0
    else
      # Get the Author for each tweet
      tweetResults.forEach (tweetInfo) ->
        count++
        ModelUser.findOne {'_id': tweetInfo.author}, (err, userInfo) ->
          tweets.push {id: tweetInfo._id, tweet: tweetInfo.tweet, created_at: tweetInfo.created_at, author: userInfo.username}

        if count == tweetResults.length
          res.render 'tweets/index', {tweets: tweets || {}}

That should get you on the right track :)

这应该让你走上正确的轨道:)