简体   繁体   中英

How to push an object into an array with GraphQL?

I would like to change the way my resolver is creating the payment cards in my DB. So now I create the wallet in one collection then a payment in another collection and use the wallet_id to in my payment to link them. But now I want to push the payments into a cards[] that is defined in wallet. Any idea how to do that in resolver?

This is my Wallet schema

const WalletSchema = new Schema({
    tokens: {
        type: Number,
        default: 0
    },
    userId: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        unique: true
    },
    cards: [
        {
            type: Schema.Types.ObjectId,
            ref: 'Payment'
        }
    ]
}, { timestamps: true });

and this is my createPayment resolver

createPayment: async (_, { wallet_id, ...args }, { user }) => {
    try {
        await requireAuth(user);
        const payment = await Payment.create({ ...args, wallet: wallet_id });

        pubsub.publish(PAYMENT_ADDED, { [PAYMENT_ADDED]: payment });

        return payment;
    } catch (error) {
        throw error;
    }
},

Any idea?

You need to create another Schema for card payments;

const WalletSchema = new Schema({
    tokens: {
        type: Number,
        default: 0
    },
    userId: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        unique: true
    },
    cards: [ PaymentSchema ] <-- here
}, { timestamps: true });

// new schema

const PaymentSchema = new Schema({
     type: Schema.Types.ObjectId,
     ref: 'Payment'
   });

Based on Wallet schema you need to write expose graphql schema

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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