Skip to content

Using default value on sub documents does not work as expected #14445

Closed

Description

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.2.2

Node.js version

20.11.1

MongoDB server version

6.3.0

Typescript version (if applicable)

No response

Description

We still don't get the correct behaviour with sub documents in our schema with mongoose 8. This it related to #14420 and the fix in #14437 did not resolve the issue.

When setting the nested document to an empty object, this get saved as null in the database. Fetching the document from the database will not fallback to the default empty object.

When setting the nested document to undefined, fetching the document from the database will return the default empty object.

This requires us to manually handle all nested paths to make sure that the values are both saved correct and use the correct return values.

Steps to Reproduce

const mongoose = require('mongoose');

const SubSchema = new mongoose.Schema({
	name: { type: String }
}, { _id: false });

const MainSchema = new mongoose.Schema({
	sub: { 
		type: SubSchema,
		default: {}
	}
});

const MainModel = mongoose.model('Main', MainSchema);

async function run() {
	await mongoose.connect('mongodb://localhost:27017/mongoose_test');
	console.log(mongoose.version);

	const doc = new MainModel({ sub: { name: 'Hello World' } });
	console.log('init', doc.sub); // { name: 'Hello World' }
	await doc.save();

	doc.set({ sub: {} });
	await doc.save();
	console.log('save empty object', doc.sub); // {} OK!

	const savedDocFirst = await MainModel.findById(doc.id).orFail();
	console.log('findById', savedDocFirst.sub); // null WRONG!

	doc.set({ sub: undefined });
	await doc.save();
	console.log('save with undefined', doc.sub); // undefined WRONG!

	const savedDocSecond = await MainModel.findById(doc.id).orFail();
	console.log('findById', savedDocSecond.sub); // {} OK!
}

run().then(() => mongoose.connection.close()).catch((error) => console.error(error));

Expected Behavior

We expect the document to have the same nested value both after save and when fetching the document form the database. And we expect the value to resolve to the default empty object (especially when explicitly setting the value to the default value)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions