【问题标题】:How to use on model into another model如何在一个模型中使用另一个模型
【发布时间】:2022-01-15 04:31:21
【问题描述】:

我有两个分开的模型名称员工和用户,它们有一些共同的数据和一个帐户 ID 来相互链接。每种型号的记录如下:

Employee
 _id:1639137618164

 name:"*****"
        
 sites:Array
 company:”Software”
 jobTitle: “Associate Software Engineer”
 email:"*****"
 phonesms:"1"
 phonevoice:"1"
 licenseNumber:""
 avatarStamp:0
 pined:false
 accountId: 1639129314021 //link attribute
 countryCodeSms:"US"
 countryCodeVoice:"US"
 inviteCode:"09611"
 emergencyRoles: Object
 invite: "booksRbUoSM"

对于用户是

_id:1639129314021

firstName:"*** ***"

lastName:"****"
companyName:"SITS"
passwordReset:""
activated:true
accountId:1639129314021 // link attribute
siteId:-1
    
role:0
    
last:1639137913873
blocked:false
blockedtext:""
trialend:1640338913781
paytype:1
hashAccess:Array
emergencyEnabled:false
visitorTypes:Array
sitesLimit:2
manualCreation:false
username:"*************"
    
password:"**********************************"
    
email:"*********************"
passwordNotification:true
passwordLifecycle:1646906375986
isNewUser:true
listFeature:Object

我想从用户模型中搜索是否存在具有该 accountId 的任何员工,是否有与 accountId 关联的员工,然后使用可用的公共数据添加新员工。否则不是。我怎样才能在环回中做到这一点。我被困在这里了!

【问题讨论】:

    标签: javascript mongodb loopbackjs


    【解决方案1】:

    我正在使用环回版本 2.x.x。原来很简单

    currentModel.app.models.modelYouWantToAccess 
    

    【讨论】:

      【解决方案2】:

      在环回 4 中

      解决方案 1:

      在您可以访问 UserRepository 的用户控制器中

      假设您知道 accountId,并且 accountId 仅在您有员工记录时才存在,您可以有一个方法

      @get('/users/{accountId})
      async findUserWhoIsAnEmployee(@param.path.string('accountId') accountId: string){
       return this.userRepository.findOne({where: {accountId}})
      }
      

      假设您不知道 accountId...

      您可以访问 UserController 中的员工存储库,方法是将其作为参数传递给构造函数并找到用户,然后签入员工记录。 (不是最优的,因为将在您的数据库上进行两次查询)

      export class UserController{
        constructor(
           @repository(UserRepository) public userRepository: UserRepository,
           @repository(EmployeeRepository) private employeeRepository: EmployeeRepository
        )
        // returns employee record or null if none
        @get('/users/{id}/employee-record)
        async findUserWhoIsAnEmployee(@param.path.string('id') id: string){
         const user = await this.userRepository.findById(id);
         return (!user) ? null : this.employeeRepository.findOne({where: {accountId: user.accountId}})
        }
      }
      

      解决方案 2:

      用户和员工模型之间存在关系(hasOne,最好是

      您可以在用户上找到该员工记录

      // returns employee record of a user if exists 
      @get('/users/{id})
      async findUserWhoIsAnEmployee(@param.path.string('id') id: string){
       return this.userRepository.findById(id).employeeRecord()
      }
      //Where employeeRecord is a reference property on the user Model.
      

      【讨论】:

      • 这是用于环回第 4 版的...但我需要第 2 版...无论如何仍然值得拥有这个!
      【解决方案3】:

      下面试试

      var  employee_data = Employee  .filter(x => User.map(y => y.accountId).includes(x.accountId));
      

      【讨论】:

      • 我认为更简单的方法是使用您在用户对象上拥有的 accountId 在员工集合中进行搜索。
      • 不是这样的……员工是从哪里来的?它们是独立的环回模型
      【解决方案4】:

      我想您正在使用猫鼬,并且您的 User 模型中有这部分:

      accountId: {
        type: mongoose.Schema.ObjectId,
        ref: 'Employee',
        required: [true, 'this field must be provided']
      },
      

      您可以将populate 方法添加到您的架构中,以便在您每次使用User.find(), findOne, 和以“find”开头的所有其他方法请求数据时添加相关模型的数据

      userSchema.pre(/^find/, function(next) {
        this.populate({
          path: 'accountId',
          options: { // you can populate only some fields if you want
            select: 'name company jobTitle'
          }
        })
      
        next()
      })
      

      然后,您可以像往常一样使用您的 User 模型,但现在添加了相关的 Employee 数据:

      const given_id = "65465458qw7d7q1q7w1x" 
      const user = await User.findOne({accountId: given_id})
      
      // Note: you can use User.find if there can be
      // more than one user with that accountId.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-27
        • 2020-06-15
        • 1970-01-01
        • 2018-09-21
        • 1970-01-01
        • 2016-10-15
        相关资源
        最近更新 更多