Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/adapters/mongoose.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ function unflatten(data) {
module.exports = (model, opts) => {
const fields = [];
const paths = unflatten(model.schema.paths);
const { virtuals } = model.schema;
const { mongoose } = opts;
// NOTICE: mongoose.base is used when opts.mongoose is not the default connection.
const Schema = mongoose.Schema || mongoose.base.Schema;
Expand All @@ -44,7 +45,7 @@ module.exports = (model, opts) => {
function detectReference(fieldInfo) {
if (fieldInfo.options) {
if (fieldInfo.options.ref && fieldInfo.options.type) {
return `${formatRef(fieldInfo.options.ref)}._id`;
return ''.concat(formatRef(fieldInfo.options.ref), `.${fieldInfo.options.foreignKey || '_id'}`);
}
if (_.isArray(fieldInfo.options.type) && fieldInfo.options.type.length
&& fieldInfo.options.type[0].ref && fieldInfo.options.type[0].type) {
Expand Down Expand Up @@ -263,6 +264,16 @@ module.exports = (model, opts) => {
function getFieldSchema(path) {
const fieldInfo = paths[path];

// update if we detect a virtual with localField
const virtual = Object.values(virtuals).find((v) => v.options && v.options.localField === path);
if (virtual) {
fieldInfo.options = {
...fieldInfo.options,
ref: virtual.options.ref,
foreignKey: virtual.options.foreignField,
};
}

const schema = { field: path, type: getTypeFromMongoose(fieldInfo) };

const ref = detectReference(fieldInfo);
Expand Down