【问题标题】:How to set property of a model from a property of a `population` field in mongoose?如何从猫鼬的“人口”字段的属性中设置模型的属性?
【发布时间】:2017-10-08 03:02:59
【问题描述】:

我有一个Post,它的author 属性通过使用ref 设置为User。假设User 中有一个country 字段,如何使Post 架构具有country 属性以及填充后来自User.country 的值。

const Post = new Schema({
    text: String,
    author: {
        type: ObjectId, 
        ref: 'User'
    },
    // How to set the virtual property country which is from User.country?
});

我知道猫鼬中有一个Populate Virtuals,但它似乎只是populating 的另一种方式,它不会获取其中一个属性,而是获取整个引用记录。还是我弄错了?

我知道我可以从Post.author.country 引用country,但我也想要Post.country

如何解决这个问题?
我可以在架构级别执行此操作吗?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    如果您使用Populate Virtuals,您可以执行以下操作:

    var schemaOptions = {
        toObject: {
            virtuals: true
        },
        toJSON: {
            virtuals: true
        }
    };
    
    var PostSchema = new Schema({
        text: String,
        id: false,
        author: {
            type: Schema.Types.ObjectId,
            ref: 'User'
        }
    }, schemaOptions);
    
    PostSchema.virtual('country').get(function() {
        return this.author.country;
    });
    

    使用:

    Post.find({}).populate('author').exec(function(error, data) {
        console.log(JSON.stringify(data));
    });
    

    它给出了:

    [{
        "_id": "59d924346be5702d16322a67",
        "text": "some text",
        "author": {
            "_id": "59d91f1a06ecf429c8aae221",
            "country": "France",
            "__v": 0
        },
        "__v": 0,
        "country": "France"
    }]
    

    查看this gist 获取完整示例

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 2016-08-25
      相关资源
      最近更新 更多