Why does Mongoose add blank arrays?

mongoose schema array of objects
mongoose schema array of strings
mongoose array default
mongoose initialize empty array
mongoose empty array
set field to null mongoose
mongoose set field empty
mongoose push

I am trying to start using Mongoose as an ODM for MongoDB with my node.js application. I have noticed that when I design a schema with an embedded document that if I don't add a value to it, it store a blank array "[]" in Mongo. Why is this? I am trying to store historical changes to records and a blank array would mean that that change deleted the value. Here is a sample schema.

schema.Client = new mongoose.Schema({
    name:{type:String, required:true},
    products:[{
        name:{type:String, index:true},
        startDate:Date,
        endDate:Date
    }],
    subdomain:{type:String, index:{unique:true}},
})

Here is the resulting document when I save a document with just name and subdomain.

{
    "name": "Smith Company",
    "products": [],
    "subdomain": "smith"
}

Why did it add products with a blank array by default and how can I stop it?

You can workaround by define the schema like below:

products: {
  type: [{
    name:String,
    startDate:Date,
    endDate:Date
  }],
  default: undefined
}

Why does Mongoose add blank arrays? - node.js - html, Ok, how do I make the default null? ;-) The usecase here is that it is expensive in mongo to request all of the Bar's that have empty foos. I have to add another� mongoose: Referencing schema in properties or arrays Written on February 01, 2015 . When using a NoSQL database like MongoDb, most of the time you'll have documents that contain all properties by itself.

Blank array gives you convenient way to add or remove elements from your Model.

$push $addToSet $pull in update would help you to manage your array elements.

If you don't have a blank array then you cannot push elements to null

But it is possible in blank array.

Empty array is saved when a property references a schema � Issue , Schemas ignore default: null for arrays, empty array is created instead. const schema = new mongoose.Schema({� Now, You want edit friends array, when you want to add or remove friend to friends array.First, we will push a friend into an array with the mongoose in nodejs app.

This seems to be by design, but there is a workaround here using a 'pre' handler to remove the default empty array: https://github.com/LearnBoost/mongoose/issues/1335

This only worked for me when I set the field to null, though. If I set it to undefined as in the sample code, the empty array seems to come back.

Unable to set array to `null` as default � Issue #6691 � Automattic , connects to the database and successfully creates 'people' with an empty friends array. To push items into mongo array via mongoose assuming,. var friend = { firstName: 'Harry', lastName: 'Potter' };. There are two options you have: Update the model in-memory, and save (plain javascript array.push):. Insert only accepts a final document or an array of documents, and an optional object which contains additional options for the collection. db.collection.insert( <document or array of documents>, { // options writeConcern: <document>, ordered: <boolean> } ) You may want to add the _id to the document in advance, but

By default the array has [] value. you can overwrite that :

var UserSchema = new Schema({
  followers : {
    type: [String],
    default: undefined
  }
})

Push items into mongo array via mongoose, an enum validator. If the value being set is not in this array, validation will fail. Note: specifying an empty array is equivalent to [Mixed] . The following all� Mongoose allows you the flexibility to create schemas with references to other schemas or, as in the above example with the ratings property, it allows you to create an Array of child properties that could be contained in a related schema (like book to author) or inline as in the above example (with book to a ratings Array). Creating and Saving

Because in your schema you are defining products to be an array of objects. You would need to try something like:

products: {
        name:{type:String, index:true},
        startDate:Date,
        endDate:Date
    },

This will store an empty object instead of an array.

Mongoose ODM, Mongoose plugins can also add custom SchemaTypes like int32. String; Number; Date; Buffer; Boolean; Mixed; ObjectId; Array; Decimal128; Map; Schema Arrays are special because they implicitly have a default value of [] ( empty array). Query an Array with Compound Filter Conditions on the Array Elements¶. The following example queries for documents where the dim_cm array contains elements that in some combination satisfy the query conditions; e.g., one element can satisfy the greater than 15 condition and another element can satisfy the less than 20 condition, or a single element can satisfy both:

Mongoose v5.9.27: SchemaTypes, How to use push and pop in mongoose with simple examples. Arrays are one of the most commonly used data structures in the programming world. They are perfect to store elements $push operator. Currently, it is empty. Suppose, we want to add a new document if the value of the _id field does not match. We can use the upsert option. The upsert option will add a new document and this new document will contain the content of the update that was passed to the findByIdAndUpdate() method. Observe the following route handler.

Push and pop in mongoose, If the sizes field does not resolve to an array but is not missing, null, or an empty array, the arrayIndex field is null . { "_id" : 1, "item"� If you haven't yet done so, please take a minute to read the quickstart to get an idea of how Mongoose works. If you are migrating from 4.x to 5.x please take a moment to read the migration guide.

$unwind (aggregation) — MongoDB Manual, Get code examples like "mongoose check if array not empty" instantly right from your find return in mongodb as an Empty array but field is present in database � not empty in mongodb INSTALL GREPPER FOR CHROME�

Comments
  • the default value for an array is an empty array, so if you save only {name:"foo",subdomain:"bar"} products will be an empty array.
  • Is there any way to change the default value for an array to result in it not writing anything?
  • can you post the code where you update your document?
  • i'm still on mongoose 2.x , you may want to have a look at mongoosejs.com/docs/api.html#model_Model-update , try setting safe to false.
  • Giving an empty array special meaning over a non-existent array is tempting, but it's a bad idea because of issues like this. It's better to add an explicit boolean flag to make the distinction you require.
  • There are still cases though where you would want the lack of an attribute to stand for "irrelevant for this document". When that is a common thing, it's an ugly waste to have a bunch of empty arrays. It seems to defeat one of the beauties of document databases, namely the ability to store different document structures in the same collection. I would like to see the ability for blank arrays to result in no attribute in the document unless a blank array is explicitly part of the model being saved. This is also intuitive. That or an explanation for why it's not possible in MongoDB.
  • Currently in mongodb $push and $addToSet will create an array if there isn't one there.
  • I want it to be an array, as one doc may contain references to multiple products. I don't want it to write anything to the database if I don't put any data in it.
  • I think this isn't even written to the database - have you checked? I had a model without an array, and when I just added an array of object ids and .findOne'd one of these Model instances the .toJSON added the empty list in the response, even though I haven't written to the database since.