首页 > 解决方案 > Mongoose Populate 不返回相关数据

问题描述

我有以下型号:

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;

const imputerSchema = new mongoose.Schema({
  dninie: {
    type: String,
    trim: true,
  },
  name: {
    type: String,
    trim: true,
    required: true,
  },
  lastname: {
    type: String,
    trim: true,
    required: true,
  },
  second_lastname: {
    type: String,
    trim: true,
  },
  phone : {
    type: Number,
    unique: true,
    trim: true,
  },
  qr: {
    type : String,
    unique: true,
    default: Date.now
  }
});

module.exports = mongoose.model('Imputer', imputerSchema)

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;

const imputationSchema = new mongoose.Schema({
  qr: {
    type: String,
    trim: true,
    required: true,
    ref: 'Imputer',
  },
  imputation_date: {
    type: String,
    default: Date.now,
    required: true,
  },
  coordinates: {
    type: [Number, Number],
    index: '2d',
  },
});

module.exports = mongoose.model('Imputation', imputationSchema);

我试图进行这样的查询:

Imputation.find()
        .populate('imputer.qr')
        .exec()
        .then(docs => console.log(docs));

我也试试

   Imputation.find()
            .populate('imputer')
            .exec()
            .then(docs => console.log(docs));

但我只得到了关于插补模型的文件,没有插补模型上的字段。

以下是文档外观的一些屏幕截图在此处输入图像描述 在此处输入图像描述

标签: mongodbmongoosemongoose-populate

解决方案


更改imputationSchema如下:

const imputationSchema = new mongoose.Schema({
  qr: {
    type: mongoose.Types.ObjectId, ref: "Imputer",
    trim: true,
    required: true,
   },
// other fields...
});

然后像这样查询:

Imputation.find()
            .populate('qr')
            .exec()
            .then(docs => console.log(docs));

推荐阅读