簡體   English   中英

用貓鼬插入多個文檔

[英]Insert multiple document with mongoose

我用express.js制作了一個API,並將mongoDB用於數據庫,將mongoose用作ODM

當我想在一次發布請求中向我的收藏夾中插入多個文檔時,我真的很困惑。

這是我的模型:

const modul = require('../config/require');
const Schema = modul.mongoose.Schema;

let TeleponSchema = new Schema({
    _pelanggan : {type: String},
    telepon: {type: String, required: true}
});

module.exports = modul.mongoose.model('telepon', TeleponSchema, 'telepon');

這是我的控制器

const Telepon = require('../models/telepon.model')

exports.create = (req,res) => {
    let telepon = new Telepon({
        _pelanggan : req.body.pel,
        telepon: req.body.telepon
    });

    telepon.save((err,data) => {
        if(err){
            res.send({message:'eror', detail: err});
        }else{
            res.send({message:'success', data: data})
        }
    });

}

然后我向郵遞員發布這樣的請求:

在此處輸入圖片說明

但是我的文檔中的結果是: 在此處輸入圖片說明

就是這個問題,“ telepon”的值在同一行中並用逗號分隔,而不是插入新行並創建新的_id

我想要這樣的收藏結果:

(例)

在此處輸入圖片說明

任何幫助和建議將不勝感激

謝謝!

1)對於每個.save調用,您只會影響一個文檔,請檢出insertMany做多個文檔。

2) req.body.telepon是數字數組,或者已經是逗號分隔的數字列表; 如果它是一個數組,則.toString仍將以逗號分隔列表。 因此,當您new Telepon時,它在一個屬性中同時具有兩個值,這就是您在結果中看到的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM