如何将对象保存到猫鼬文档

How to save object to a mongoose document

我正在使用 mongodb,我在保存方面遇到了挑战。

我的架构是

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'}
})

在我的控制器中,我正在这样做

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

如何将交易类型与发件人和收件人一起保存。

非常感谢

WalletTransactiontransaction 架构的模型吗?您可以这样做来保存文档:

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

我不得不将模型更改为

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'}
})

在保存时,我这样做了

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