猫鼬删除空对象或数组 [英] mongoose remove empty objects or arrays

查看:81
本文介绍了猫鼬删除空对象或数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,其中的字段有时在保存时为空.我最初的想法是删除预保存中的空白字段,但是由于某些原因似乎无法正常工作.保存后,对象值仍然存在.

I have an object which has fields that are sometimes empty on save. My initial thought was to remove empty fields on pre-save, but for some reason that doesn't seem to be working. The object values are still there after they are saved.

module.exports = function(req, res, next) {
var newRecipe = new Recipe(req.body);

newRecipe.pre('save', function (next) {

  var that = this.data;

  Object.keys(that.data).forEach(function(key) {
    if(that.data.hasOwnProperty(key)){
      if(typeof that.data[key] != 'undefined'){
        if (!that.data[key].length){
          delete that.data[key];
       };
    }
  }
});

  next(); 
});

newRecipe.save(function(err, recipe) {
  if (err) {
    console.log(err);
    res.sendStatus(500);
  } else {
    res.sendStatus(200);
  }
}); 
 };

这是我的传入对象:

  { 
  notes: [],
  isHostessGift: false,
  playbook: {},
  location: {},
  wine: { ingredient: false, pairing: false },
  coupons: [],
  ingredients: [{ item: 'd' }],
  categories: { dishType: ["Beverage"], mainIngredient: ["d"] },
  directions: [{ step: 'd' }],
  serves: 9,
  cookTime: 9,
  prepTime: 8,
  headline: 'ccc' 
}

有更好的方法吗?

出于某些原因,从chridam的答案开始工作,继承的属性正在通过hasOwn属性函数传递.

Working from chridam's answer for some reason inherited properties are passing through the hasOwn Property function.

 var hasOwnProperty = Object.prototype.hasOwnProperty;

function isPropertyEmpty(obj) {
if (obj == null)       return true;
if (obj.length > 0)    return false;
if (obj.length === 0)  return true;
for (var key in obj) {
    if (hasOwnProperty.call(obj, key)){
        console.log(key);
    } 
}
return true;


}



module.exports = function(req, res, next) {
    var newRecipe = new Recipe(req.body);

newRecipe.pre('save', function (next) {

 var doc = this;
  Object.keys(doc).forEach(function(key) {
      if (isPropertyEmpty(doc[key])){
          // console.log(_.omit(doc, doc[key]));
      };
  }); 

 console.log(doc); 


  next(); 
});

整理文档:

strictMode
selected
shardval
saveError
validationError
adhocPaths
removing
inserting
version
getters
_id
populate
populated
wasPopulated
scope
activePaths
ownerDocument
fullPath
emitter
createdAt
sites
published
featured
data
_id
slug
image
$__original_save
save
$__original_save
save
{ image: 'lol.jpg',
  slug: 'lol',
  _id: 561522878ff1d2f9ae9b4323,
  data: 
   { headline: 'lol',
     prepTime: 22,
     cookTime: 6,
     serves: 8,
     directions: [ [Object] ],
     categories: { mainIngredient: [Object], dishType: [Object] },
     ingredients: [ [Object] ],
     coupons: [],
     wine: { pairing: false, ingredient: false },
     location: {},
     playbook: {},
     isHostessGift: false,
     notes: [] },
  featured: false,
  published: false,
  sites: [ 'HOL' ],
  createdAt: Wed Oct 07 2015 09:47:51 GMT-0400 (EDT) }

推荐答案

当存在带有可选Array字段的嵌套模式时,此解决方案存在很多问题.我通过创建一个新类型解决了这个问题:

I was having a lot of problems with this solution when there were nested schemas with optional Array fields. I solved this by creating a new type:

optional_array = 
  type: Mixed
  validate: 
    validator: (v) ->
      return v instanceof Array
    message: '{VALUE} needs to be an array.'

,然后将我的所有字段都设置为optional_array而不是Array.

and then setting all my fields to optional_array instead of Array.

这篇关于猫鼬删除空对象或数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆