Alex Ironside
Alex Ironside

Reputation: 5039

Omit unnecessary properties in mongodb

I have this model:

var accountSchema = new mongoose.Schema({
    'seeker': {
        'fullName': String,
        'ageGroup': String,
        'education': String,
        'lookingForWork': String,
        'employmentStatus': String,
        'resume': String, // Filename ans stuff
        'mainWorkExp': String,
    },
    'employer': {
        'activationStatus': String,
        'companyName': String,
        'contactPersonFullName': String,
        'companyWebsite': String,
        'hiringRegion': [String],
        'logo': [],
        'description': String,
        'industry': String,
        'workingWithEOSP': Boolean,
        'booth': {
            'exists': Boolean, // Boolean to store with the employer created his/her booth or not
            'numberVisits': Number // number of clicks on the particular booth
            /* We can add more attributes here as we go */
        }
    },
});

It is exported and all is great. But there is one problem. If I try to create a seeker account using this script:

new account({
    'seeker': {
        'fullName': r.fullName,
        'ageGroup': r.ageGroup,
        'education': r.education,
        'lookingForWork': r.lookingForWork,
        'employmentStatus': r.employmentStatus,
        'mainWorkExp': r.mainWorkExp,
        'resume': r.file,
    },
}),
r.password,

In effect I get this in the database:

{
    "_id": {
        "$oid": "5b4689ab6d68e81d32fda65e"
    },
    "seeker": {
        "fullName": "Alex Ironside",
        "ageGroup": "18 - 24",
        "education": "Some High School",
        "lookingForWork": "Less than 1 month",
        "employmentStatus": "Unemployed",
        "mainWorkExp": "Business, Finance or Administration. Includes all levels of office admin, accounting/bookkeeping, human resources, banking, etc."
    },
    "employer": { // The problem is right here!
        "hiringRegion": [],
        "logo": []
    }
}

So as you can see, I'm not mentioning the logo, or hiringRegion anywhere in the code, but it still gets created. Why is that? Does it have to do with the fact they're both declared as an array in the model? And how can I get around this issue?

I basically don't want the employer property/object to be created in the document created by my code. It should be only the seeker object, but I cannot just delete the logo and hiringRegions from the model, because I'm using them somewhere else, as an array.

The r object is short for req.body.

Upvotes: 0

Views: 37

Answers (1)

vkarpov15
vkarpov15

Reputation: 3872

Mongoose arrays implicitly have a default value of empty array so you can start using the array immediately. Do this instead:

'hiringRegion': { type: [String], default: undefined },
'logo': { type: [], default: undefined }

Upvotes: 1

Related Questions