2

I'm trying to setup a default array size and value in my mongoose schema, but the return is always appearing as [] unless the document actually has data.

"transform": { type: [ Number ], default: [0, 0, 0] }

Return value is:

"transform":[]

How do I configure my schema so it returns:

"transform":[0,0,0]

Answer: Setting required: true will add the data to any new documents created. Old documents will not be updated, however.

"transform": { type: [ Number ], default: [0, 0, 0], required: true }

Update To quickly resolve my data issue I ran an update on Mongo to upgrade all existing documents using the following line.

db.getCollection('objects').updateMany(
    { "properties.transform": []}, 
    { $set: { "properties.transform" : [0,0,0] }}
);

NOTE: My transform field is a child of properties hence the "properties.transform"

3
  • 1
    zero is seen as empty Commented Mar 10, 2017 at 22:12
  • Is there anyway to override that? I suppose I could use 1,1,1 (just tested and it works), but it's not ideal. Commented Mar 10, 2017 at 22:15
  • Possible duplicate of Why doesn't my schema to add default values in mongoose arrays? Commented May 15, 2017 at 10:18

1 Answer 1

1

Well its either you set required to true in the schema. Or false, which defaults to empty. You can't have both ways in this case either empty or provide a value.

A hack you could use is this. Just set required to true, and upon data entry initially push array of zeroes.

model.push([0,0,0]);
Sign up to request clarification or add additional context in comments.

2 Comments

Got it, I was testing on previously generated documents, I just ran an update with default set to 0 and required true, and the new documents have returned [0,0,0]
nice bro! previously generated documents caused it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.