23

For my project i've created an userSchema which simplified looks like the following:

var userSchema = new Schema({
    _id: String,
    screenname: {type: String, required: false, default: "equal _id"},
});

The user has an _id that is a string which also is his username. Everything works so far until i tried to add an extra field screenname. What i want is when the user creates an account, his screenname equals the value of _id. Later he can adjust it but by default it should equal the value of _id. i've also tried :

 screenname: {type: String, required: false, default: _id},

But than ofcourse _id is not defined.

How should i set the default value to equal another value ?

2 Answers 2

32

use the pre middleware explained here

userSchema.pre('save', function (next) {
    this.screenname = this.get('_id'); // considering _id is input by client
    next();
});
Sign up to request clarification or add additional context in comments.

Comments

16

You can pass a function to default, following is a schema field excerpt:

username: {
    type: String,
    required: true,
    // fix for missing usernames causing validation fail
    default: function() {
        const _t = this as any; // tslint:disable-line
        return _t.name || _t.subEmail;
    }
},

3 Comments

This worked wonderful for me, @Prop({ type: String, required: false, default: function () { return this.name || this.email.split('@')[0]; }, }) name: string;
There's a catch in this. You can not use arrow functions for the default value. For eg. the below code will always return the same value which is 7. default: () => Math.random(). // lets say output 0.7
@Ram as per latest version (7.5.0) you can use arrow functions. This code in my case generates random uuid's every time I call create: uuid: { type: String, default: () => crypto.randomUUID() }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.