【问题标题】:Populate multiple level does not work填充多个级别不起作用
【发布时间】:2016-07-04 15:31:36
【问题描述】:
First = new mongoose.Schema({
  name: String,
  second: {type: Schema.Types.ObjectId, ref: 'Second'},
});

Second = new mongoose.Schema({
  name: String,
  third: {type: Schema.Types.ObjectId, ref: 'Third'},
});


Third = new mongoose.Schema({
  name: String
});

First.find({}).populate({
  path: 'Second',
  populate: { path:  'Third'}
  }).exec(function(err, result) {
    console.log(result)
    })

第一个填充没问题,但第三个总是null。意思是我得到了这样的东西:

{
  name: 1,
  second: {
    name: 2,
    third: null

    }}

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate mongoose-schema


    【解决方案1】:
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    mongoose.connect('mongodb://localhost/test');
    
    var FirstSchema = new mongoose.Schema({
      name: String,
      second: {type: Schema.Types.ObjectId, ref: 'Second'},
    });
    
    var SecondSchema = new mongoose.Schema({
      name: String,
      third: {type: Schema.Types.ObjectId, ref: 'Third'},
    });
    
    
    var ThirdSchema = new mongoose.Schema({
      name: String
    });
    
    var First = mongoose.model('First', FirstSchema);
    var Second = mongoose.model('Second', SecondSchema);
    var Third = mongoose.model('Third', ThirdSchema);
    
    First.remove({}).exec();
    Second.remove({}).exec();
    Third.remove({}).exec();
    
    var _3 = new Third({name: 'third'});
    _3.save(function(err1) {
      if (err1) {
        throw err1;
      }
      var _2 = new Second({name: 'second', third: _3.id});
      _2.save(function(err2) {
        if (err2) {
          throw err2;
        }
        var _1 = new First({name: 'first', second: _2.id});
    
        _1.save(function() {
          First.find({}).populate({
            path: 'second',
            populate: { path:  'third'}
          }).exec(function(err, result) {
            console.log(result[0]);
          });
        });
      });
    });
    

    您的path 是否被分配了错误的值或什么?

    它应该是一个字段名,而不是一个对象名

    【讨论】:

    • 原谅回调地狱?
    • 那些.remove() 调用是个问题,因为您没有等待回调完成。这意味着这很可能会在您查询数据之前擦除数据。一般原则是正确的 "field name not model name" 用于路径。如果您只是发布文本输出而不是屏幕截图,那也很好。
    猜你喜欢
    • 2019-08-14
    • 2020-10-17
    • 2016-06-27
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    相关资源
    最近更新 更多