如何使用GraphQL在MongoDB中插入没有现有数据的多个数组对象

时间:2019-07-19 16:28:57

标签: javascript mongodb mongoose graphql

当前graphql解析器将插入用户数据。我只需要在成员数据库中不存在id(id!= member_id)时,才将多个数组对象插入MongoDB。

需要插入的数据

[
  {
    first_name: "Mate",
    id: 402335654,
    is_bot: false,
    language_code: "ml"
  }, {
    first_name: "testerbot",
    id: 357622799,
    is_bot: false,
    username: "testergroupbot"
  }, {
    first_name: "machan",
    id: 1225612,
    is_bot: false,
    language_code: "ml",
    username: "alavalathi"
  }
]

当前解析器

createMember: async args => {
  try {
    const existMember = await Member.findOne({
      member_id: args.memberInput.member_id,
    });
    if (existMember) {
      throw new Error('This user already exist');
    }
    const member = new Member({
      member_id: args.memberInput.member_id,
      first_name: args.memberInput.first_name,
      last_name: args.memberInput.last_name,
      username: args.memberInput.username,
      date: new Date(args.memberInput.date),
    });

    const result = await member.save();
    // eslint-disable-next-line no-underscore-dangle
    return { ...result._doc };
  } catch (error) {
    throw error;
  }
},

作为graphql和mongodb的新手,对其有了一个很好的了解。

1 个答案:

答案 0 :(得分:0)

该解决方案随附insertMany()

createMember: async args => {
  try {
    const newMembers = await args.memberInput.map(arg => ({
      member_id: arg.member_id,
      first_name: arg.first_name,
      last_name: arg.last_name,
      username: arg.username,
      date: new Date().toISOString(),
    }));

    const results = await Member.insertMany(newAdmins);
    return results.map(result => {
      return { ...result._doc };
    });
  } catch (error) {
    throw error;
  }
},