Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js mongoose默认值等于其他值_Node.js_Mongodb - Fatal编程技术网

Node.js mongoose默认值等于其他值

Node.js mongoose默认值等于其他值,node.js,mongodb,Node.js,Mongodb,对于我的项目,我创建了一个userSchema,它简化了如下内容: var userSchema = new Schema({ _id: String, screenname: {type: String, required: false, default: "equal _id"}, }); 用户有一个_id,它是一个字符串,也是他的用户名。 到目前为止一切都正常,直到我尝试添加一个额外的字段屏幕名。我想要的是,当用户创建一个帐户时,他的屏幕名等于_id的值。以后他可以调整它

对于我的项目,我创建了一个userSchema,它简化了如下内容:

var userSchema = new Schema({
    _id: String,
    screenname: {type: String, required: false, default: "equal _id"},
});
用户有一个_id,它是一个字符串,也是他的用户名。 到目前为止一切都正常,直到我尝试添加一个额外的字段屏幕名。我想要的是,当用户创建一个帐户时,他的屏幕名等于_id的值。以后他可以调整它,但默认情况下它应该等于_id的值。我也尝试过:

 screenname: {type: String, required: false, default: _id},
但是,当然,id并没有定义


如何将默认值设置为等于另一个值?

使用
pre
中间件


您可以将函数传递给默认值,以下是架构字段摘录:

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;
    }
},
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;
    }
},