node.js - 如何保存猫鼬虚拟
问题描述
谁能提供示例如何保存 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
这样吗?或者它是如何工作的?
解决方案
Virtuals 是您可以获取和设置但不会持久保存到 MongoDB 的文档属性。getter 可用于格式化或组合字段,而 setter 可用于将单个值分解为多个值以进行存储。
这意味着我们可以仅将 Virtuals 用于数据准备,例如我们可以合并first name
和last name
/或使用参考填充文档。
推荐阅读
- sql - 使用 SQL 有条件地提取固定宽度数据
- html - 缩小浏览器窗口时将 flexbox 放在一起
- python-2.7 - Selenium Python 脚本,InvalidElementStateException
- javascript - 将 JavaScript 滚动顶部更改为 id 或类而不是正文
- wordpress - Redux 框架数组选项值
- android - 未解决的 Android 依赖项
- shell - (g)awk:在 system() 中使用 GNU 的日期
- python - 使用openCV在远程服务器上的视频缩略图
- javascript - 通过循环调用多个描述
- python - 使用 BeautifulSoup从封装标签中获取内容