Re: [mongoose] Ignore propery if value is null or empty

6,911 views
Skip to first unread message

Aaron Heckmann

unread,
Dec 26, 2012, 2:24:29 PM12/26/12
to mongoo...@googlegroups.com
I don't know what BsonIgnoreIfNull or the other .net specific stuff does exactly, but I'll share a few things that may help.

Mongoose has no means to drop data automatically. If you'd like to remove a property from a document (using $unset), you can assign the property `undefined` and then `.save()` it.

   console.log(doc.name) // Hobbit
   doc.name = undefined;
   doc.save() // sends { $unset: { name: 1 }}

Mongoose supports pre save hooks which you could use to inspect values and assign `undefined` if necessary.

  schema.pre('save', function (next) {
    if (null == this.property) {
      this.property = undefined; // will cause an $unset
    }
    next();
  })

Mongoose schemas support plugins, that is, you are free to write reusable logic and apply it to any schema you like. So you could take whatever you write in the pre save hook about and reuse it across all of your schemas.

Mongoose documents support transformations when JSON.stringifying or calling .toObject() on them. This allows you to convert the document into anything you want. Read more about them here: http://mongoosejs.com/docs/api.html#document_Document-toObject



On Wed, Dec 26, 2012 at 2:10 AM, Максим Пономарев <mvpon...@gmail.com> wrote:
I tried to find but I can't… Is there a way to ignore some properties of schema if Its value undefined, null or empty?

For exampe I have:
var SectionSchema = new Schema({
    caption: String,
    address: Number,
    counters: [Number],
    errors: {
        casset: [String],
        main: [String],
        dupl: [String]
    },
    warnings: {
        main: [String],
        dupl: [String]
    }
});

And several records in DB:
== 1 ==
{
    caption: "One",
    address: 1001,
    error: {
        main: [ERR_CHN_A]
    }
}

== 2 ==
{
    caption: "Two",
    address: 2002,
    counters: [24,24],
    warnings: {
        main: [SHIELD_DEV_B, SHIELD_DEV_C],
        dupl: [SHIELD_DEV_B]
    }
}

As you can see records may contain not all properties of schema. 
And instead these records I recive:
== 1 ==
{
    caption: "One",
    address: 1001,
    counters: [],
    error: {
        cassete: [],
        main: [ERR_CHN_A],
        dupl: []
    },
    warnings: {
        main: [SHIELD_DEV_B, SHIELD_DEV_C],
        dupl: [SHIELD_DEV_B]
    }
}

== 2 ==
{
    caption: "Two",
    address: 2002,
    counters: [24,24],
    errors: {
        cassete: [],
        main: [],
        dupl: []
    },
    warnings: {
        main: [SHIELD_DEV_B, SHIELD_DEV_C],
        dupl: [SHIELD_DEV_B]
    }
}

In ASP.NET WebAPI there is ignore conditions:
public class SectionState
{
    [BsonIgnoreIfNull]
    public string caption { get; set; }

    public int address { get; set; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public List<int> counters { get; set; }

    [BsonIgnoreIfNull]
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public EssoSectionErrors errors { get; set; }

    [BsonIgnoreIfNull]
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public EssoSectionWarnings warnings { get; set; }
}

Is there something like this in Mongoose?

--
--
http://mongoosejs.com - docs
http://plugins.mongoosejs.com - plugins search
http://github.com/learnboost/mongoose - source code
 
You received this message because you are subscribed to the Google
Groups "Mongoose Node.JS ORM" group.
To post to this group, send email to mongoo...@googlegroups.com
To unsubscribe from this group, send email to
mongoose-orm...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/mongoose-orm?hl=en
 
 



--
Aaron


Aaron Heckmann

unread,
Dec 28, 2012, 11:07:44 AM12/28/12
to mongoo...@googlegroups.com
Its hard to say without seeing your code. Is your objective is to overwrite the entire document each time?

On Wednesday, December 26, 2012, Максим Пономарев wrote:
I play with schema.pre('save') and .toObject({ transform: true }) and see that mongoose doesn't insert missing in POST request fields of simple types (String, Number), but fields 'typeof' Array or Object are inserting with empty values. I think it's not quite right.

var schama = new Schema({
  caption
: String,
  counters
: [Number],
  error
: {

    main
: [String],
    dupl
: [String]
 
}
})


$
.post(url, { counters: [2,2] });
/* Saved document
{
  counters: [2,2],
  error: {
    main: [],
    dupl: []
  }
}
*/

I think that if the field is missing in the POST request, it should not appear in the saved document.

четверг, 27 декабря 2012 г., 1:24:29 UTC+6 пользователь Aaron Heckmann написал:


--
Aaron



Message has been deleted

Максим Пономарев

unread,
Dec 28, 2012, 11:19:09 PM12/28/12
to mongoo...@googlegroups.com
> Is your objective is to overwrite the entire document each time?

I have collection which contains documents that will never update (only adding and getting). But these documents include different information within schema: one document may contain counters:[] field and contain no other fields, some other document may not contain this field but contain fields error:{ main:[], dupl:[] } and warning:{ main:[], dupl:[] }, some docs may contain only one part of error or warning objects, for example, error:{ main:[] } or warning:{ dupl:[] }.

пятница, 28 декабря 2012 г., 22:07:44 UTC+6 пользователь Aaron Heckmann написал:
mongoose-orm+unsubscribe@googlegroups.com

For more options, visit this group at
http://groups.google.com/group/mongoose-orm?hl=en
 
 


--
Aaron



Reply all
Reply to author
Forward
0 new messages