简体   繁体   English

如何使用 GraphQL 在 MERN 应用程序中插入 MongoDB 模式中的数组字段?

[英]How can you insert into an array field in a MongoDB schema in a MERN application using GraphQL?

I am learning how to develop using MongoDB, express, react, node and GraphQL.我正在学习如何使用 MongoDB、express、react、node 和 GraphQL 进行开发。 I have researched a lot and am having issues grasping one concept.我已经研究了很多,但在掌握一个概念时遇到了问题。 My application is basically a recipe app where users are able to CRUD recipes and have an online cookbook collection of them.我的应用程序基本上是一个食谱应用程序,用户可以在其中 CRUD 食谱并拥有它们的在线食谱集合。

With this in mind I created this schema:考虑到这一点,我创建了这个架构:

const CookbookProfileSchema = mongoose.Schema({
    fName: String,
    lName: String,
    email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
    password: String,
    cookbook: [{
      recipe: {
        rTitle: String,
        rDescription: String,
        rCookTime: String,
        rIngredients: [{
          iName: String,
          iMeasurement: String,
        }],
        rInstructions: [{
          text: String
        }]
    }
  }]    
});

I have only used SQL databases until now, and I have found tutorials showing me how to create 2 different schemas with a relationship but at that point wouldn't I just be better off with a relational database?到目前为止,我只使用过 SQL 数据库,我找到了一些教程,向我展示了如何创建 2 个具有关系的不同模式,但在这一点上,使用关系数据库不是更好吗?

These are my type definitions:这些是我的类型定义:

const typeDefs = `
  type Query {
    userProfiles: [UserProfile]
    userLookup(id: ID!): [UserProfile]
    userLogin(email: String, password: String): [UserProfile]
  }
  type UserProfile{
    id: ID!
    fName: String
    lName: String
    email: String
    password: String
    cookbook: [Recipe]
  }

  type Recipe{
    rTitle: String
    rDescription: String
    rCookTime: String
    rIngredients: [Ingredient]
    rInstrctions: [Instruction]
  }

  type Ingredient{
    iname: String
    iMeasurement: String
  }

  type Instruction{
    text: String
  }

  type Mutation {
    createUser(fName: String, lName: String, email: String, password: String): UserProfile
    removeUser(id: ID!): Boolean
    updateUser(id: ID!, fName: String, lName: String): Boolean
    updatePassword(id: ID!, password: String): Boolean
  }
` 

And these are my resolvers so far:到目前为止,这些是我的解析器:

const resolvers = {
  Query: {
    userProfiles: () => UserProfile.find(),
    //userLogin: async (_, {id}) => await UserProfile.findById(new ObjectID({id}))
    userLookup: (_, {id}) => UserProfile.find(ObjectId(id)),
    userLogin: (_, email, password) => UserProfile.find(email, password)
  },
  Mutation: {
    //User CRUD Mutations
    createUser: async (_, {fName, lName, email, password }) => {
      const user = new UserProfile({ fName, lName, email, password, cookbook: null});
      await user.save();
      return user;
    },
    removeUser: async (_, {id}) => {
      await UserProfile.findByIdAndRemove(id);
      return true;
    },
    updateUser: async (_,{id, fName, lName}) => {
      //Code in front end to check if the fname or lname is null
      await UserProfile.findByIdAndUpdate(id, {fName , lName });
      return true;
    },
    updatePassword: async (_, {id, password}) => {
      await UserProfile.findByIdAndUpdate(id, { password });
      return true;
    },

  }
}

const server = new GraphQLServer({ typeDefs, resolvers })
mongoose.connection.once('open', function() {
  server.start(() => console.log('Server is running on localhost:4000'))
});

I am intending for a user to have many recipes, a recipe can have many ingredients and many instructions so I can display it in a list type format that they can check off for just that session or state.我打算让用户有很多食谱,一个食谱可以有很多成分和很多说明,所以我可以以列表类型的格式显示它,他们可以只检查那个会话或状态。 In a relational database I would have a table for recipes and have them relate the user.在关系数据库中,我会有一个食谱表,并让它们与用户相关联。 Instructions and ingredients would be related to the recipe.说明和成分将与食谱有关。 Then for the view I would simply query all the recipes belonging to that user to make the cookbook.然后对于视图,我将简单地查询属于该用户的所有食谱来制作食谱。 How could I do something similar here or should I just go the relational route?我怎么能在这里做类似的事情,还是应该走关系路线? I really want to experience how to use mongodb to it's fullest though.不过,我真的很想体验如何充分利用 mongodb。

Any help or advice would be greatly appreciated!任何帮助或建议将不胜感激!

I guess you already found out you don't have the hasMany , belongTo etc relationship methods in MongoDB.我猜你已经发现你在 MongoDB 中没有hasManybelongTo等关系方法。 However, it is possible for you to model the relational-type relationships with MongoDB.但是,您可以使用 MongoDB 对关系类型的关系进行建模。 Check here . 检查这里

Although, I should stress that "having as many tables as possible to represent the different data entities(data normalization)" like we do for SQL databases might not be a good schema design for NoSQL databases like MongoDB.虽然,我应该强调,像我们对 SQL 数据库所做的那样, “拥有尽可能多的表来表示不同的数据实体(数据规范化)”对于像 MongoDB 这样的 NoSQL 数据库来说可能不是一个好的模式设计。 Most times, you are better off having documents that are related to each other together.大多数情况下,最好将相互关联的文档放在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM