简体   繁体   English

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

[英]Populate() ref nested in object array

I am trying to populate() all the subscriptions in my User model with data from the Show model. 我试图用Show模型中的数据填充()User模型中的所有订阅。 I have tried .populate('subscriptions.show') but it does nothing to the results. 我已经尝试过.populate('subscriptions.show'),但它对结果没有任何作用。

If I make subscriptions a plain array of Refs like so 如果我像这样进行订阅,就会得到一系列简单的Ref

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

doing a populate('subscriptions') works as intended 做一个populate('subscriptions')按预期工作

I have looked at every similar question I could find on Stackoverflow and what I could find on the docs. 我看过我在Stackoverflow上可以找到的每个类似问题以及在文档中可以找到的东西。 I can't see what I am doing wrong. 我看不到我在做什么错。

complete test file source that i am working with https://gist.github.com/anonymous/b7b6d6752aabdd1f9b59 我正在使用的完整测试文件源https://gist.github.com/anonymous/b7b6d6752aabdd1f9b59

Schema and Models 模式和模型

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

Initial Data 初始数据

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

The Query 查询

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

    console.log(user);
  });

results in: 结果是:

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

Some code perhaps, also some corrections to your approach. 也许有一些代码,对您的方法也有一些更正。 You kind of want a "manyToMany" type of join which you can make as follows: 您有点想要“ 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) );
          });


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

});

That should show a populated response much like this: 那应该显示一个填充的响应,就像这样:

{
    "_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
        }
    ]
}

Or without the "manyToMany" works also. 还是没有“ manyToMany”的作品也。 Note here that there is no initial call to populate: 请注意,这里没有要填充的初始调用:

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


        });
    });
  });

});

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM