Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose default value equal to other value

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 ?

like image 949
Sven van den Boogaart Avatar asked Apr 29 '15 18:04

Sven van den Boogaart


People also ask

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

What is findById in mongoose?

In MongoDB, all documents are unique because of the _id field or path that MongoDB uses to automatically create a new document. For this reason, finding a document is easy with Mongoose. To find a document using its _id field, we use the findById() function.

What is Mongoose types ObjectId?

Types. ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.

Does Mongoose auto generate ID?

_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.


2 Answers

use the pre middleware explained here

userSchema.pre('save', function (next) {
    this.screenname = this.get('_id'); // considering _id is input by client
    next();
});
like image 85
codeofnode Avatar answered Sep 22 '22 00:09

codeofnode


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;
    }
},
like image 36
ekerner Avatar answered Sep 21 '22 00:09

ekerner