简体   繁体   中英

Mongoose Save Nested Array of Objects - Node.js

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保存的数据

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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM