Skip to content

Mongoose object in a sub array object not being set in Mongoose 6.0.13 #11011

Closed
@richardlay

Description

@richardlay

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

What is the current behavior?

Illustrating the issue through an example, say we have the following schemas:

const TransactionSchema = new Schema({
    payments: [
        {
            id: { type: String },
            terminal: {
                _id: { type: Schema.Types.ObjectId, ref: "Terminal" },
                name: { type: String }
            } 
        }
    ]
});   

const TerminalSchema = new Schema({
    name: { type: String },
    apiKey: { type: String }
});

If you push an object to the payments array, where the object contains a terminal model object, the terminal field gets chopped. For example:

const Transaction = Mongoose.model("Transaction");
const Terminal = Mongoose.model("Terminal");
const transaction = new Transaction();
const terminal = new Terminal({
    name: "Front desk",
    apiKey: "somesecret"
});
transaction.payments.push({
    id: "testPayment",
    terminal: terminal
});

transaction.payments[0].terminal does not exist.
The transaction object looks like this:

{
    payments: [
        {
            id: "testPayment"
        }
    ]
}

If the current behavior is a bug, please provide the steps to reproduce.

What is the expected behavior?

Using Mongoose 5.13.3, under the same scenario above, transaction.payments[0].terminal exists.
The transaction object looks like this:

{
    payments: [
        {
            id: "testPayment",
            terminal: {
                _id: <some bson ID>,
                name: "Front desk"
            } 
        }
    ]
}

This behaviour was useful because we could store a snapshot of a model in a different collection and pick the fields we wanted using the Schema definition. In this example we don't want to snapshot the sensitive apiKey field.

Is there a way to keep this behaviour in Mongoose 6.0.13?

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

Node 16.3.0
Mongoose 6.0.13
MongoDB 4.2.17

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