如何创建猫鼬子模型而不为其创建集合

问题描述 投票:0回答:2
const walletTransactionSchema = new mongoose.Schema({
        a: {type: Boolean, required: true},   
    },
    {timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}});

const walletSchema = new Schema({
    b: {type: Boolean, required: true},       
    transactions: [{type: walletTransactionSchema}],
});

walletSchema.index({'transactions': 1}, {sparse: true});   


module.exports.Wallet = mongoose.model('Wallet', walletSchema, 'wallets');
module.exports.WalletTransaction = mongoose.model('WalletTransaction', walletTransactionSchema);

我正在尝试为子文档(WalletTransaction)创建模型,而不为其创建集合。不幸的是,猫鼬会自动创建该集合。如何防止这种行为并仅定义子模型而不创建集合。我更喜欢通过重构来组织我的模式,而不是仅仅嵌入它们。 我曾经这样做过,上面的定义没有任何问题。我想更新到 mongoose 6.0.8(从 5.13 开始)后就会发生这种情况。

node.js mongodb mongoose mongoose-schema
2个回答
0
投票

如果你想在模型中创建另一个模型 您应该采用以下方法

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    email: {
        type: String,
        required: true},
    about:{type:String},
    password: {type: String, required: true},
    friends: [new mongoose.Schema({
        user: {type: String}
    }, {strict: false})],
    profileImage: {type: String, default: "default.jpg"},
    userName: {type: String, required: true},
    matches: {type: Number, default: 0},
    wins: {type: Number, default: 0},
    losses: {type: Number, default: 0},
    backgroundImage: {type: String, default: "default.jpg"},
    resetPasswordToken: {type: String, required: false},
    resetPasswordExpires: {type: Date, required: false},
    isDeleted: {type: Boolean, default: false},
    deletedAt: {type: Date, default: null},
}, {timestamps: true}, {strict: false});

module.exports = mongoose.model('User', userSchema);

像这样,我在我的用户模型中创建另一个名为 Friends 的模型,其中每个条目都有 one 特定的 id


0
投票

对于子文档,您不需要实际创建模型而只需架构。然后,当您想要添加子文档(在您的情况下为事务)时,只需传递与架构匹配的对象即可。这将阻止创建子文档集合。

这里有一个关于它的 github 问题 - https://github.com/Automattic/mongoose/issues/11498

© www.soinside.com 2019 - 2024. All rights reserved.