Skip to content

No access to "this" in default function for Array type #6840

@teddav

Description

@teddav

Do you want to request a feature or report a bug?
bug

What is the current behavior?
When trying to set a default on an Array field, the default function doesn't give me access to the current object being created. I want to fill the array differently depending on the other values.
I found a similar issue #6263
But it is recommended to access pre-hooks, which I can't do. I need to have access to the default field.
Im using the latest version of mongoose (5.2.7).

Im using the same example as in the mongoose doc http://mongoosejs.com/docs/defaults.html#default-functions-and-this
I just added a field "actors" which is an array.
In releaseDate, I have access to this , but not in actors

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const schema = new Schema({
	title: String,
	released: Boolean,
	releaseDate: {
		type: Date,
		default: function() {
			console.log("releaseDate: ", this.released);
			if (this.released) {
				return Date.now();
			}
			return null;
		}
	},
	actors: {
		type: [
			{
				name: String,
				age: Number
			}
		],
		default: function() {
			console.log("actors: ", this.released);
			return [
				{
					name: "Test",
					age: 20
				}
			];
		}
	}
});

const Movie = mongoose.model("Movie", schema);

const movie1 = new Movie({ title: "The Terminator", released: true });
const movie2 = new Movie({ title: "The Legend of Conan", released: false });

console.log(movie1);

Metadata

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