[英]Save an array of a model in mongodb using mongoose and nodejs
I am using nodejs and mongoose to save data in mongodb.我正在使用 nodejs 和 mongoose 将数据保存在 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?我希望它保存这种数据格式: [{gatePassSchema},{gatePassSchema}....] 我在网上找到的大多数实现都展示了如何将 model 中的元素转换为数组,但是如果我想使用整个 model 怎么办作为一个数组?
First you will need to convert your schema into a model:首先,您需要将架构转换为 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.之后,您只需在阵列上运行 array.map 并创建 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.这应该返回一个数组,您的 JSON object 应该转换为 mongoose 模型。 Is this what you needed?这是你需要的吗?
More on array map:有关阵列 map 的更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.