【问题标题】:Insert a document with mongoose without initialize the model with empty attributes使用 mongoose 插入文档而不用空属性初始化模型
【发布时间】:2019-04-04 18:20:08
【问题描述】:

我想在我的数据库中插入一个网站表单中的文档。我有一个用 mongoose 创建的模型,我只想将包含数据的属性保存在数据库中,我不想保存空属性。

这是我的模型:

const localizationSchema = new Schema({
    name: { type: String, required: true },
    spins: [{ type: String }],
    spinsForChild: [{ type: String }],
    parent: { id: String, name: String },
    localizationType: { type: String },
    count: { type: Number, default: 0 },
    countries: [{ id: String, name: String, cities: [{ id: String, name: String }] }]
});

const Localization = mongoose.model('Localization', localizationSchema);

当我尝试保存一个新文档时,它会在数据库中创建所有属性,尽管我没有在我的查询中发送它。

 Localization.create({
    name: body.name,
    localizationType: body.localizationType,
    "parent.id": parent.id,
    "parent.name": parent.name,
    spins: spins,
    spinsForChild: spinsForChild
}, function(err) {
    if (err) return handleError(err);
    res.redirect('/localizations');
});

例如,此代码在数据库中插入一个名为“国家”的空数组。

我尝试在模型声明中使用 strict: false 但它不起作用。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以使用this answer。

    但是,您尝试实现的东西似乎是反模式的,当您尝试将array update operators 与undefined 数组一起使用时可能会导致错误。所以,请谨慎使用。

    祝你好运!

    【讨论】:

    • 我只需要这个属性在我的应用程序内部使用,我会小心的。谢谢!
    猜你喜欢
    • 2015-08-03
    • 2013-12-16
    • 2020-01-18
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    相关资源
    最近更新 更多