在 Mongoose Schema 中创建一个字段,该字段是对同一文档中其他字段的引用

gsa*_*nac 6 mongoose mongodb node.js

因此,如果修改原始字段,复制的字段也会更改。

伪代码示例:

userSchema = {
    firstName: {type: String},
    lastName: {type: String},
    displayName: firstName + ' ' + lastName
}
Run Code Online (Sandbox Code Playgroud)

这样的事情可能吗?

编辑:我需要根据该字段发出请求,所以我不能在检索它们时只连接这些字段。

Bar*_*rno 5

您可以使用挂钩http://mongoosejs.com/docs/middleware.html

userSchema = {
    firstName: {type: String},
    lastName: {type: String},
    displayName: {type: String}
}

userSchema.pre('save', function(next) {
    this.displayName = this.username+' '+this.lastName;
    next();
});
Run Code Online (Sandbox Code Playgroud)