猫鼬填充不返回相关数据

时间:2019-07-18 19:55:09

标签: mongodb mongoose mongoose-populate

我有以下型号:

identical(resultA,resultB)

然后我尝试进行如下查询:

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

但是我只有归因模型上的文档而没有归因模型上的字段。

以下是文档外观的屏幕截图enter image description here enter image description here

1 个答案:

答案 0 :(得分:0)

按以下步骤更改您的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));