【问题标题】:Can't push the object to the array in Graphql无法将对象推送到 Graphql 中的数组
【发布时间】:2020-04-29 21:56:12
【问题描述】:

我无法将我的产品对象推送到我的购物车数组中,我不知道该怎么做。 任何人都知道如何解决这个问题? 我收到此错误:Cannot return null for non-nullable field Mutation.addToShopping。

用户模型:

import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        unique: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    cart: {
        type: Array,
    }
});

userSchema.set('toObjenct', { viruals: true });

var Users = mongoose.model('User', userSchema);

module.exports = Users;

解析器:

addToShopping: async (parent, args, context, info) => {
            const userId = getUserId(context);
            const product = await Products.findById(args.id);
            console.log(product)
            const user = await Users.findByIdAndUpdate(userId, { $push: { cart: product } }, { new: true }).exec()
                .catch((err) => {
                    console.log(err)
                });
            return user;
        },

架构:

type User {
        id: ID!
        name: String!
        email: String!
        password: String!
        cart: [Product]!
    }
type Product {
        id: ID!
        name: String!
        type: String!
        price: String!
        quantity: String!
    }

【问题讨论】:

  • 你有没有在产品中得到任何产品?就像根据您的架构一样,您的购物车值应该是一个数组。
  • 是的,我有,我可以单独创建一个产品,但我无法将它连接到我的用户

标签: mongodb mongoose graphql


【解决方案1】:

Tnx 我找到了答案:)

addToShopping: async (parent, args, context, info) => {
            const userId = await getUserId(context);
            const product = await Products.findById(args.id);
            const values = {};
            Object.entries(args).forEach(([key, value]) => {
                if (value) {
                    values[key] = value;
                }
            });
            const user = await Users.findByIdAndUpdate(userId, {
                $set: values,
                $push: {
                    cart: {
                        id: args.id,
                        name: product.name,
                        type: product.type,
                        price: product.price,
                        quantity: product.quantity
                    }
                }
            }, {
                new: true,
                safe: true,
                upsert: true
            }).exec()
                .catch((err) => {
                    console.log(err)
                });
            return user;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 2020-12-20
    • 2018-11-21
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多