0

我正在尝试填充“子文档”,其想法是构建启用路径的对象Session.Groups[0].Members[0]._user.pseudo (Session.Groups -> User),这是我尝试过的,2 种不同的方法,有 2 个不同的问题:

  • 第一个不填充任何内容(甚至不是“第一个文档(组)”)。
  • 第二个在我填充Session.Groups[0].Members[0]._user === null 后给我。

我在这里看到了有关如何执行操作的答案,但在我的情况下它不起作用。我刚刚将猫鼬更新到 v3.8.0。

var UserSchema = new mongoose.Schema({
  pseudo: { type: String, required: true, unique: true }
)};
Db['User'] = db.model('User', UserSchema);

var GroupSchema = new mongoose.Schema({
  Members: [ 
    { _user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, points: { type: Number, required: true, default: -1 } },
    { _user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, points: { type: Number, required: true, default: -1 } },
    { _user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, points: { type: Number, required: true, default: -1 } }
  ]
});
Db['Group'] = db.model('Group', GroupSchema);

var SessionSchema = new mongoose.Schema({
  date: { type: Date, required: true, default: Date.now },
  Groups: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Group' }]
});
Db['Session'] = db.model('Session', SessionSchema);

情况1

Db['Session']
.find()
.populate('Groups.Member._user') // I get anything populate (not even the Groups).
.exec(function(err, Sessions) {
    var nb_populated = Sessions.length;
    for (var Session in Sessions)
        Sessions[Session].populate('Groups.Members._user', function(err, Res) {
            if (err)
                console.error('Error when populating Groups.Members._user');

            nb_populated--;
            if (!nb_populated) {
                console.log(JSON.stringify(Res.Groups)); //Here, i just get the Groups ids
                res.send(200, Res);
            }
        });

案例#2

Db['Session']
.find()
.populate('Groups')
.exec(function(err, Sessions) {
    var nb_populated = Sessions.length;
    for (var Session in Sessions)
        Sessions[Session].populate('Groups.Members._user', function(err, Res) {
            if (err)
                console.error('Error when populating Groups.Members._user');

            nb_populated--;
            if (!nb_populated) {
                console.log(JSON.stringify(Res.Groups)); //Here, every Members._user become `=== null` (wasn't befor the `populate()` call).
                res.send(200, Res);
            }
        });
4

0 回答 0