1

I've created my model and can save an array of objects by manually listing them out, however this won't work in production because my array will not always be the same size.

Below is an example of my code. The issue I'm having when saving an array of objects under the stackRank field.

If anyone has any suggestions that would be great and a life saver!

Mongoose Model

const MySchema = mongoose.Schema({
  userId: {type: mongoose.Schema.Types.ObjectId, ref: 'User', require: true},
  startDate: {type: Date, require: true},
  endDate: {type: Date, require: false}, 
  length: {type: Number, require: true},
  inProgress: {type: Boolean, require: true, default: true}, 
  stackRank:[{
    appUsers: {type: mongoose.Schema.Types.ObjectId, ref: 'Users', require: true}
  }]
});

Saving Code in Express

const mySchema = new MySchema({  
      userId: req.body.userId,
      startDate: today,
      length: req.body.startLength,
      stackRank: [          //TODO this is the part I need to change
        {appUsers: Array[0]}, 
        {appUsers: Array[1]},
        {appUsers: Array[2]}
      ]
    });

    instantComp.save()
    .then((result) => {
      console.log('result from save', result)
    })
    .catch(err => console.log('error promise all', err))

Desired Functionality

Instead of saving each value of the array individually for the field appUsers nested in stackRank, I want to be able to save the entire array at once because it will not always have a length of three. It will almost always vary in length so while the code I've written works for an array of this size, it won't actually function properly for me.

Picture of how I want the data to be saved in Mongo MongoDB Saved Data

1
  • 1
    Can you create the array + push all the objects to it first? and then add it in mySchema? Commented Feb 14, 2019 at 22:32

1 Answer 1

5

You can try this modification to your current code

let stackRank = []; 
for(let elem of array) //array is your array variable, i suppose
    stackRank.push({appUsers: elem}); 

mySchema.stackRank = stackRank; 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Mehdi ! My issue making sure I passed in a JS array of Objects that matched what was in the database. I didn't think about creating the array of objects with the appUsers key beforehand. Thanks for your help, this will really make a big difference in many spots in my app going forward!

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.