是否可以以编程方式添加.populate()?

问题描述 投票:0回答:1

我正在为我的应用创建数据库服务,但需要一些代码。人口众多。因此可以添加如下内容:

if (populateFriends) {
  .populate('friends')
}
if (populatePosts) {
  .populate('posts')
}

并添加结尾,它将自动将其添加到find()。populate('friends')。populate('posts');

因为现在我得到了这样的东西:

  Action.find({ completed: false, userRole: ROLES.ADMIN }, selection)
    .populate({
      path: 'tender',
      select: 'number description shipper carriers type',
      populate: {
        path: 'shipper',
        select: 'company firstName lastName',
        populate: {
          path: 'company',
          select: 'companyName'
        }
      }
    })
    .sort({ creationDate: -1 })
    .populate('additionalData.documentId'),
javascript mongoose mongoose-populate
1个回答
0
投票

您已经证明了,实际上不能用条件语句破坏方法链。我认为更好的方法是将参数分配给变量,然后在函数调用中使用该参数:var类型;

if (populateFriends) {
  type = 'friends';
}
if (populatePosts) {
  type = 'posts';
}

Action.populate(type);
© www.soinside.com 2019 - 2024. All rights reserved.