javascript - 如何从另一个参考模型填充猫鼬虚拟?
问题描述
// define a schema
const personSchema = new Schema({
name: {
first: String,
last: String
}
},
{
toJSON: {
virtuals: true,
},
toObject: {
virtuals: true,
},
},);
personSchema.virtual('fullName').
get(function() {
return this.name.first + ' ' + this.name.last;
}).
set(function(v) {
this.name.first = v.substr(0, v.indexOf(' '));
this.name.last = v.substr(v.indexOf(' ') + 1);
});
// compile our model
const Person = mongoose.model('Person', personSchema);
这是来自定义#virtuals的文档
让我们有另一个引用 Person 的模型:
const shopSchema = new Schema({
name:String,
owner: { type: Schema.Types.ObjectId, ref: "Person" },
});
const Shop = mongoose.model('Shop', shopSchema);
现在,如何fullName
在商店填充虚拟物品owner
。这里,所有者不包括fullName
const getAllData = async () => {
const shops = await Shop.find().populate("owner").lean();
console.log(shops)
}
解决方案
根据猫鼬文档:
使用lean() 绕过所有Mongoose 特性,包括virtuals、getter/setter 和默认值。如果你想用lean()来使用这些特性,你需要使用相应的插件。
因此,fullName
已从返回的数据中删除。获取fullName
virtuals 的简单方法是将查询更改为以下内容:
const getAllData = async () => {
const shops = await Shop.find()
.populate({
path: 'owner',
options: {
lean: false
}
})
.lean();
console.log(shops);
};
它不会lean()
在内部使用,populate
或者您可以完全禁用lean()
。
推荐阅读
- sql - 根据 id 匹配的另一个表中的值更新表中的列
- python - 如何在python中利用字节数组的每一位
- java - Java MicroService 需要访问 postgres 表而不通过端点暴露数据
- python - 忽略基于子字符串的某些打印语句
- google-chrome - Chrome 不保存有关内容的设置 > 本地文件的弹出窗口
- pandas - DataFrame的行和列之间的迭代以计算平均值
- haskell - 当在 C 中管理(取消)分配时,Haskell 运行时中的垃圾收集器问题
- python - 如何使用 Python(Win32 模块)使 Visio 形状的文本对齐
- node.js - 将数据从 EJS 发布到 Node.js
- javascript - 将 javascript 箭头函数更改为 typesctipt