首页 > 解决方案 > 如何保存猫鼬虚拟

问题描述

谁能提供示例如何保存 mongoose virtuals 以供数据库关联使用?

已经在模型中有这个:

const userSchema = new Schema({
    googleId: String,
    name: String,
    email: String,
    password: String,
    credits: {type: Number, default: 0},
});

userSchema.virtual('advertisements', {
    ref: 'advertisements',
    localField: '_id',
    foreignField: '_id',
    justOne: false,
    options: { sort: { name: -1 }, limit: 5 }
  });

mongoose.model('users', userSchema);

在文档中有关于数据填充和检索的信息,但是应该如何正确保存?

它必须是user.advertisements.localfield = localfield这样吗?或者它是如何工作的?

标签: node.jsexpressmongoose

解决方案


Virtuals 是您可以获取和设置但不会持久保存到 MongoDB 的文档属性。getter 可用于格式化或组合字段,而 setter 可用于将单个值分解为多个值以进行存储。

这意味着我们可以仅将 Virtuals 用于数据准备,例如我们可以合并first namelast name/或使用参考填充文档。


推荐阅读