【问题标题】:Save an array of a model in mongodb using mongoose and nodejs使用 mongoose 和 nodejs 在 mongodb 中保存模型数组
【发布时间】:2020-10-22 09:25:09
【问题描述】:

我正在使用 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}....] 我在网上找到的大多数实现都展示了如何将模型中的元素转换为数组,但是如果我想将整个模型用作数组呢?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

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

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

    之后,您只需在数组上运行 array.map 并创建模型的实例。

    类似这样的:

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

    这应该返回一个数组,您的 JSON 对象应该在其中转换为猫鼬模型。这是你需要的吗?

    更多关于数组映射:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

    【讨论】:

    • 非常感谢! array.map 对我有用。它在数据库中保存为单独的实例。我为此使用了for循环,有没有更好的方法? for(i=0; i<gatePasses.length; i++) { try { await gatePasses[i].save() .then(item => { // res.json(item) console.log('New GatePass added w/ id: ',item.id) })
    • 您可以使用yourArray.forEach。为此,您可以阅读更多内容:medium.com/@JeffLombardJr/…
    • 这确实有效,但有没有办法将其保存为数组而不是将数组元素保存为单独的实例?如果我将它们保存为单独的实例,那么当我必须检索它们时编写 get api 会非常困难,因为我想将它们作为数组检索
    • 您可以将所有内容放在我发布的第一个数组映射中。除了调用 new GatePass,您还可以扩展它来保存元素并执行请求。最后,您返回结果。如果您稍后需要 gatePass 元素数组,那么您还可以在该数组上调用单独的数组映射,这样您将获得所需的结果数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 2023-04-10
    • 2016-12-11
    相关资源
    最近更新 更多