I am using nodejs and mongoose to save data in mongodb. I have a schema like this. I want to save an array which has these objects as array elements
const gatePassSchema = new mongoose.Schema({
sno: {
type: String,
required: true
},
modeOfTransport: {
type: String,
required: true
},
description: {
type: String,
required: true
},
quantity: {
type: Number,
required: true
},
unit: {
type: String,
required: true
},
issuedTo: {
type: String,
required: true
},
dateOfReturn: {
type: Date,
required: true
},
from: {
type: String,
required: true
},
to: {
type: String,
required: true
},
reason: {
type: String,
required: true
},
remark: {
type: String,
required: true
},
incomingRef: {
type: String,
required: true
}
})
The request body coming to the server looks like this:
[ { sno: '1',
modeOfTransport: 'oijoi',
description: 'oiouiu',
quantity: 5,
unit: 'number',
issuedTo: 'giug',
dateOfReturn: '2020-07-12T18:30:00.000Z',
from: 'iuhiu',
to: 'hiuhi',
reason: 'hiu',
remark: 'ih',
incomingRef: 'iuhilk' },
{ sno: '2',
modeOfTransport: 'avvss',
description: 'uihiuhiu',
quantity: 6,
unit: 'packet',
issuedTo: 'giukh',
dateOfReturn: '2020-07-05T18:30:00.000Z',
from: 'iuhi',
to: 'uihnvn',
reason: 'lop',
remark: 'ytfyvh',
incomingRef: 'psd' } ]
I want it to save this data format: [{gatePassSchema},{gatePassSchema}....] Most implementations I found online show how to turn an element in the model into an array, but what if I want to use the whole model as an array?
First you will need to convert your schema into a model:
var GatePass = mongoose.model('GatePass', gatePassSchema);
after that you just need to run array.map on your array and create instances of your model.
Something like this:
yourArray.map(element => new GatePass(element));
This should return an array where your JSON object should be converted into mongoose models. Is this what you needed?
More on array map:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
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.