typeORM黑名单用户

时间:2019-03-30 16:25:50

标签: javascript node.js typeorm

在我的社交应用程序中,用户可能想将用户列入黑名单(就像很多社交应用程序一样)。

我有2个实体:

用户 (但已列入黑名单的用户) ManyToOne 黑名单

用户许多对黑名单

用户:

@Entity()
@Unique(["username"])
export class User 
{
@PrimaryGeneratedColumn()
id: number;

@Column()
@Length(4, 20)
username: string;

@Column()
@Length(4, 100)
password: string;

@Column()
@IsNotEmpty()
role: string;

@Column()
@CreateDateColumn()
createdAt: Date;

@OneToMany(type => Blacklist, blacklist => blacklist.user)
blacklist: Blacklist[];

@ManyToMany(type => Blacklist)
@JoinTable({
  "name": "user_blacklist"
})
blacklists:Blacklist[]

@Column()
@UpdateDateColumn()
updatedAt: Date;

hashPassword() {
  this.password = bcrypt.hashSync(this.password);
}

checkIfUnencryptedPasswordIsValid(unencryptedPassword: string) {
  return bcrypt.compareSync(unencryptedPassword, this.password);
}
}

黑名单:

@Entity()
export class Blacklist {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToOne(type => User, user => user.blacklist)
  user: User;
}

这是我在 post('user / blacklist')

上调用的方法
static addBlacklist = async (req: Request, res: Response) => {
  const { id, blacklisted_id } = req.body;

  const blacklistRepository = getRepository(Blacklist);
  const userRepository = getRepository(User);

  let user: User
  let blacklistedUser: User;
  try {
    user = await userRepository.findOneOrFail(id);
    blacklistedUser = await userRepository.findOneOrFail(blacklisted_id);
  } catch(error) {
    res.status(404).send({error: error});
  }
  let blacklist = new Blacklist();
  blacklist.user = blacklistedUser;
  // user.blacklists.push(blacklist);

  try {
    await blacklistRepository.save(blacklist);
    await userRepository.save(user);
    res.status(201).send('success blacklisted');
  } catch (error) {
    res.status(404).send({error: error});
  }
}

它适用于黑名单,我有一个包含黑名单用户ID的新黑名单。但我无法添加user_blacklist(希望我很清楚)

所以我尝试添加:

user.blacklists.push(blacklist); // see above comment

但我知道

  

(节点:40495)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“ push”

实际:

blacklist // works
+------------+--------------+
| id         | userId       |
+------------+--------------+
| 1          | 1            |
+------------+--------------+
user_blacklist // not works cause of cannot push and save
+------------+--------------+
| userId     | blacklistId  |
+------------+--------------+
| Empty                     |
+------------+--------------+

预期:(因此用户#2从用户#1列入黑名单)

blacklist
+------------+--------------+
| id         | userId       |
+------------+--------------+
| 1          | 2            |
+------------+--------------+
user_blacklist
+------------+--------------+
| userId     | blacklistId  |
+------------+--------------+
| 1          | 1            | 
+------------+--------------+

感谢帮助

1 个答案:

答案 0 :(得分:1)

您需要这样做:

user.blacklists = [blacklist];

,然后保存用户实体。

有关更多信息,请在这里https://github.com/typeorm/typeorm/blob/master/docs/many-to-many-relations.md