繁体   English   中英

使用 mongoose 和 nodejs 在 mongodb 中保存 model 的数组

[英]Save an array of a model in mongodb using mongoose and nodejs

我正在使用 nodejs 和 mongoose 将数据保存在 mongodb 中。 我有这样的架构。 我想保存一个将这些对象作为数组元素的数组

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
    }

})

到达服务器的请求正文如下所示:

 [ { 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' } ]

我希望它保存这种数据格式: [{gatePassSchema},{gatePassSchema}....] 我在网上找到的大多数实现都展示了如何将 model 中的元素转换为数组,但是如果我想使用整个 model 怎么办作为一个数组?

首先,您需要将架构转换为 model:

var GatePass = mongoose.model('GatePass', gatePassSchema);

之后,您只需在阵列上运行 array.map 并创建 model 的实例。

像这样的东西:

yourArray.map(element => new GatePass(element));

这应该返回一个数组,您的 JSON object 应该转换为 mongoose 模型。 这是你需要的吗?

有关阵列 map 的更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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