Home > Back-end >  How to save object to a mongoose document
How to save object to a mongoose document

Time:03-21

I am using mongodb and I am having challenges saving.

My Schema is

const transaction = new Schema({
    sender: {
        type: ObjectId,
        default: null,
        transaction_type: {
            type: String,
            enum: transaction_types,
            default: null
        }
    },
    recipient: {
        type: ObjectId,
        default: null,
        transaction_type: {
            type: String,
            enum: transaction_types,
            default: null
        }
    },
    coins: {
        type: Number
    },
    fee: {
        type: Number,
        default: 0
    },
}, {
    timestamps: {createdAt: 'created_at', updatedAt: 'updated_at', deleted_at: 'deleted_at'}
})

In my controller, I am doing this

await WalletTransaction.create({
                sender: user._id,
                recipient: recipient,
                coins: coins
            });

How do I save the transaction type alongside the sender and recipient.

Thanks a lot

CodePudding user response:

Is WalletTransaction the model of the transaction schema? you may do this to save the document:

const t = await WalletTransaction.create({
                sender: user._id,
                recipient: recipient,
                coins: coins
            });
await t.save();

CodePudding user response:

I had to change my model to

const transaction = new Schema({
    sender: {
        user: {
            type: ObjectId,
            default: null,
        },
        transaction_type: {
            type: String,
            enum: transaction_types,
            default: null
        }
    },
    recipient: {
        user: {
            type: ObjectId,
            default: null,
        },
        transaction_type: {
            type: String,
            enum: transaction_types,
            default: null
        }
    },
    coins: {
        type: Number
    },
    fee: {
        type: Number,
        default: 0
    },
}, {
    timestamps: {createdAt: 'created_at', updatedAt: 'updated_at', deleted_at: 'deleted_at'}
})

and on saving, I did this

await WalletTransaction.create({
    sender: {
        user: user._id,
        transaction_type: "sent"
    },
    recipient: {
        user: recipient,
        transaction_type: "received"
    },
    coins: coins
});
  • Related