首页 > 解决方案 > 如何从另一个参考模型填充猫鼬虚拟?

问题描述

 // 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)
}

标签: javascriptnode.jsmongodbmongoose

解决方案


根据猫鼬文档

使用lean() 绕过所有Mongoose 特性,包括virtuals、getter/setter 和默认值。如果你想用lean()来使用这些特性,你需要使用相应的插件。

因此,fullName已从返回的数据中删除。获取fullNamevirtuals 的简单方法是将查询更改为以下内容:

const getAllData = async () => {
  const shops = await Shop.find()
    .populate({
      path: 'owner',
      options: {
        lean: false
      }
    })
    .lean();
  console.log(shops);
};

它不会lean()在内部使用,populate或者您可以完全禁用lean()


推荐阅读