添加文档时如何从mongoDB中删除空白字段?

时间:2019-07-17 13:12:32

标签: node.js mongodb mongoose mongoose-schema

我想从文档中删除语言。

  const departmentSchema = new mongoose.Schema({
  Depart: { type: String, required: true, minlength: 5, maxlength: 50 },
  Languages: [languageSchema]
});

enter image description here

我已经尝试过Languages: { type: [languageSchema], required: false },但是没有运气。

先谢谢您了:)

2 个答案:

答案 0 :(得分:0)

minimize选项设置为false,如果猫鼬有任何空对象,它将删除此字段,或尝试将值设置为undefined


const departmentSchema = new mongoose.Schema({
  Depart: { type: String, required: true, minlength: 5, maxlength: 50 },
  Languages: [languageSchema],
  { minimize: false }
});

或者您可以在前端应用程序上检查是否有任何语言添加language

const data;
if(departament.languages.length > 0) {
  data.language = departament.languages;
}

答案 1 :(得分:0)

一如既往地亲自找到解决方案:p

const departmentSchema = new mongoose.Schema({
  Depart: { type: String, required: true, minlength: 5, maxlength: 50 },
  Languages: [languageSchema]
});

departmentSchema.pre('save', function (next) {
  if (this.isNew && 0 === this.Languages.length) {
    this.Languages= undefined;                                                                                                                                   
  }
  next();
})

这可以解决问题。 ^