Populate()ref嵌套在对象数组中

时间:2014-06-23 05:00:14

标签: javascript node.js mongodb mongoose

我正在尝试使用Show模型中的数据填充()我的User模型中的所有订阅。我试过.populate(' subscriptions.show')但它对结果没有任何作用。

如果我订阅一个简单的Refs数组,那么

subscriptions: [{type: Schema.Types.ObjectId, ref: 'Show'}]

执行填充('订阅')按预期工作

我已经查看了Stackoverflow上可以找到的每个类似问题以及我在文档上可以找到的内容。我无法看到我做错了什么。

我正在使用https://gist.github.com/anonymous/b7b6d6752aabdd1f9b59

的完整测试文件来源

架构和模型

var userSchema = new Schema({
  email: String,
  displayName: String,
  subscriptions: [{
    show: {type: Schema.Types.ObjectId, ref: 'Show'},
    favorite: {type: Boolean, default: false}
  }]
});

var showSchema = new Schema({
  title: String,
  overview: String,
  subscribers: [{type: Schema.Types.ObjectId, ref: 'User'}],
  episodes: [{
    title: String,
    firstAired: Date
  }]
});

var User = mongoose.model('User', userSchema);
var Show = mongoose.model('Show', showSchema);

初始数据

var user = new User({
  email: "test@test.com",
  displayName: "bill"
});

user.save(function(err, user) {
  var show = new Show({
    title: "Some Show",
    overview: "A show about some stuff."
  });

  show.save();
  user.subscriptions.push(show);
  user.save();
});

查询

User.findOne({
  displayName: 'bill'
})
  .populate('subscriptions.show')
  .exec(function(err, user) {
    if (err) {
      console.log(err);
    }

    console.log(user);
  });

结果:

{
  _id: 53a7a39d878a965c4de0b7f2,
  email: 'test@test.com',
  displayName: 'bill',
  __v: 1,
  subscriptions: [{
    _id: 53a7a39d878a965c4de0b7f3,
    favorite: false
  }]
}

2 个答案:

答案 0 :(得分:1)

也许有些代码,也是对你的方法的一些修正。你想要一个" manyToMany"您可以按如下方式进行的联接类型:

var async = require("async"),
    mongoose = require("mongoose"),
    Schema = mongoose.Schema;


mongoose.connect('mongodb://localhost/user');


var userSchema = new Schema({
  email: String,
  displayName: String,
  subscriptions: [{ type: Schema.Types.ObjectId, ref: 'UserShow' }]
});

userShows = new Schema({
  show: { type: Schema.Types.ObjectId, Ref: 'Show' },
  favorite: { type: Boolean, default: false }
});

var showSchema = new Schema({
  title: String,
  overview: String,
  subscribers: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  episodes: [{
    title: String,
    firstAired: Date
  }]
});


var User = mongoose.model('User', userSchema);
var Show = mongoose.model('Show', showSchema);
var UserShow = mongoose.model('UserShow', userShows);

var user = new User({
  email: 'test@test.com',
  displayName: 'bill'
});

user.save(function(err,user) {

  var show = new Show({
    title: "Some Show",
    overview: "A show about some stuff."
  });

  show.subscribers.push( user._id );
  show.save(function(err,show) {
    var userShow = new UserShow({ show: show._id });
    user.subscriptions.push( userShow._id );
    userShow.save(function(err,userShow) {
      user.save(function(err,user) {
        console.log( "done" );
        User.findOne({ displayName: "bill" })
          .populate("subscriptions").exec(function(err,user) {

          async.forEach(user.subscriptions,function(subscription,callback) {
              Show.populate(
                subscription,
                { path: "show" },
              function(err,output) {
                if (err) throw err;
                callback();
              });

          },function(err) {
            console.log( JSON.stringify( user, undefined, 4) );
          });


        });
      });
    });
  });

});

这应该显示一个像这样的填充响应:

{
    "_id": "53a7b8e60462281231f2aa18",
    "email": "test@test.com",
    "displayName": "bill",
    "__v": 1,
    "subscriptions": [
        {
            "_id": "53a7b8e60462281231f2aa1a",
            "show": {
                "_id": "53a7b8e60462281231f2aa19",
                "title": "Some Show",
                "overview": "A show about some stuff.",
                "__v": 0,
                "episodes": [],
                "subscribers": [
                    "53a7b8e60462281231f2aa18"
                ]
            },
            "__v": 0,
            "favorite": false
        }
    ]
}

或没有" manyToMany"也有效。请注意,没有初始调用填充:

var async = require("async"),
    mongoose = require("mongoose"),
    Schema = mongoose.Schema;


mongoose.connect('mongodb://localhost/user');


var userSchema = new Schema({
  email: String,
  displayName: String,
  subscriptions: [{
    show: {type: Schema.Types.ObjectId, ref: 'UserShow' },
    favorite: { type: Boolean, default: false }
  }]
});


var showSchema = new Schema({
  title: String,
  overview: String,
  subscribers: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  episodes: [{
    title: String,
    firstAired: Date
  }]
});


var User = mongoose.model('User', userSchema);
var Show = mongoose.model('Show', showSchema);

var user = new User({
  email: 'test@test.com',
  displayName: 'bill'
});

user.save(function(err,user) {

  var show = new Show({
    title: "Some Show",
    overview: "A show about some stuff."
  });

  show.subscribers.push( user._id );
  show.save(function(err,show) {
    user.subscriptions.push({ show: show._id });
    user.save(function(err,user) {
        console.log( "done" );
        User.findOne({ displayName: "bill" }).exec(function(err,user) {

          async.forEach(user.subscriptions,function(subscription,callback) {
              Show.populate(
                subscription,
                { path: "show" },
              function(err,output) {
                if (err) throw err;
                callback();
              });

          },function(err) {
            console.log( JSON.stringify( user, undefined, 4) );
          });


        });
    });
  });

});

答案 1 :(得分:0)

检查答案:https://stackoverflow.com/a/28180427/3327857

  Car   .find()   .populate({
    path: 'partIds',
    model: 'Part',
    populate: {
      path: 'otherIds',
      model: 'Other'
    }   
 })