Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(datasource-mongoose): when combining asModels and asFields, collection.create returns invalid records for subcollections #763

Merged
merged 1 commit into from Jul 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 5 additions & 4 deletions packages/datasource-mongoose/src/collection.ts
Expand Up @@ -104,9 +104,9 @@ export default class MongooseCollection extends BaseCollection {
if (this.stack.length < 2) {
const { insertedIds } = await this.model.insertMany(data, { rawResult: true });

return flatData.map((record, index) => ({
return flatData.map((flatRecord, index) => ({
_id: replaceMongoTypes(insertedIds[index]),
...record,
...flatRecord,
}));
}

Expand All @@ -125,7 +125,8 @@ export default class MongooseCollection extends BaseCollection {
const updates: Record<string, { rootId: unknown; path: string; records: unknown[] }> = {};
const results = [];

for (const record of data) {
for (const [index, record] of data.entries()) {
const flatRecord = flatData[index];
const { parentId, ...rest } = record;
if (!parentId) throw new ValidationError('Trying to create a subrecord with no parent');

Expand All @@ -138,7 +139,7 @@ export default class MongooseCollection extends BaseCollection {

results.push({
_id: `${rootId}.${path}.${updates[rootIdString].records.length - 1}`,
...record,
...flatRecord,
});
}

Expand Down
Expand Up @@ -21,7 +21,9 @@ export default async function setupFlattener(dbName = 'test') {
}),
horsePower: String,
owner: { type: Schema.Types.ObjectId, ref: 'companies' },
comments: [{ date: Date, comment: String }],
comments: [
{ date: Date, comment: String, nested: { subNested: String, subNested2: String } },
],
companies: [{ type: Schema.Types.ObjectId, ref: 'companies' }],
},
company: { type: Schema.Types.ObjectId, ref: 'companies' },
Expand Down
Expand Up @@ -131,6 +131,44 @@ describe('Complex flattening', () => {
);
});

/** @see https://community.forestadmin.com/t/bug-report-with-smart-models-on-node-js-agent/6480/6 */
it('should work when creating a submodel with nested fields', async () => {
const flatRecord = {
date: '2010-01-01T00:00:00.000Z',
comment: 'hi!',
'nested@@@subNested': 'hi!',
'nested@@@subNested2': 'hi!',
};

connection = await setupFlattener('collection_flattener_create');

const dataSource = new MongooseDatasource(connection, {
flattenMode: 'manual',
flattenOptions: {
cars: {
asFields: ['engine.comments.nested'],
asModels: ['engine.comments'],
},
},
});

const [car] = await dataSource.getCollection('cars').create(caller, [{ name: 'my fiesta' }]);
const [carCommentFromApp] = await dataSource
.getCollection('cars_engine_comments')
.create(caller, [{ parentId: car._id, ...flatRecord }]);

const carSeenFromDb = await connection.model('cars').findOne({ _id: car._id });

expect(carCommentFromApp).toMatchObject(flatRecord);
expect(carSeenFromDb.engine.comments[0]).toEqual(
expect.objectContaining({
date: expect.any(Date),
comment: 'hi!',
nested: { subNested: 'hi!', subNested2: 'hi!' },
}),
);
});

it('creating a subModel should fail', async () => {
connection = await setupFlattener('collection_flattener_create');

Expand Down