Node.js 如何通过mongoose中的引用对象属性检索对象

Node.js 如何通过mongoose中的引用对象属性检索对象,node.js,mongoose,Node.js,Mongoose,我有一个对象钱包,其参考属性为公司 const walletSchema = new Schema( { type: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'WalletType' }, owner: { type: mongoose.Schema.Types.ObjectId, required: true,

我有一个对象
钱包
,其参考属性为
公司

  const walletSchema = new Schema(
  {
    type: {
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      ref: 'WalletType'
    },
    owner: {
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      ref: 'Company'
    },      {
    timestamps: { createdAt: 'created_at', updatedAt: 'last_updated' }
  }
);



 const companySchema = new Schema({
  name: {
    type: String,
    maxlength: 50,
    required: true
  },
  staff_size: {
    type: Number,
  }
)

我正试图用一个特定的公司名称来获取钱包。下面是我的问题,但似乎不起作用

await this.find({owner: { name : { $regex: term, $options: 'i' }}})
         .populate(
           {
             path: 'type',
             select: '_id name'
           },
           {
             path: 'owner',
             select: 'name'
           }
         )
        .sort({ last_updated: -1 })
        .exec();

对于模型“Wallet”

的路径“owner”处的值“{name:{'$regex':'Gambeat','$options':'I'}”,我得到错误
CastError:Cast to ObjectId失败,因为在填充之前首先执行查询。在查询模型时,所有者名称尚未填充

await this.find({owner: { name : { $regex: term, $options: 'i' }}})
         .populate(
           {
             path: 'type',
             select: '_id name'
           },
           {
             path: 'owner',
             select: 'name'
           }
         )
        .sort({ last_updated: -1 })
        .exec();
您可以做的是,在填充所有者时,只使用所述名称填充所有者。这应该起作用:

let wallets = await this.find({}).populate(
               {
                 path: 'type',
                 select: '_id name'
               },
               {
                 path: 'owner',
                 match: {name: { $regex: term, $options: 'i' }},
                 select: 'name _id'
               }
             )
            .sort({ last_updated: -1 })
            .exec();
这仍然会返回所有钱包,但会有一些公司字段为空。因此,您可以筛选以仅获取公司不为空的

wallets = wallets.filter((wallet) => wallet.company)