简体   繁体   English

用猫鼬插入多个文档

[英]Insert multiple document with mongoose

I made an API with express.js, and i use mongoDB for my database and mongoose as my ODM 我用express.js制作了一个API,并将mongoDB用于数据库,将mongoose用作ODM

I really confused when i want to insert multiple document to my collection in once post request. 当我想在一次发布请求中向我的收藏夹中插入多个文档时,我真的很困惑。

Here my model : 这是我的模型:

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');

and here my controller 这是我的控制器

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})
        }
    });

}

Then i post my request with postman like this : 然后我向邮递员发布这样的请求:

在此处输入图片说明

but the result in my document is : 但是我的文档中的结果是: 在此处输入图片说明

that's the problem, the value of 'telepon' is in the same row and separated by comma instead of insert a new row and create a new _id 就是这个问题,“ telepon”的值在同一行中并用逗号分隔,而不是插入新行并创建新的_id

i want the result of my collection like this : 我想要这样的收藏结果:

(example) (例)

在此处输入图片说明

Any help and suggestion would be much appreciated 任何帮助和建议将不胜感激

Thank you! 谢谢!

1) Per .save call you will only affect one document, check out insertMany to do multiple. 1)对于每个.save调用,您只会影响一个文档,请检出insertMany做多个文档。

2) req.body.telepon is either an array of numbers, or is already just the comma delimited list of numbers; 2) req.body.telepon是数字数组,或者已经是逗号分隔的数字列表; if it is an array the .toString will result in a comma delimited list anyways. 如果它是一个数组,则.toString仍将以逗号分隔列表。 So when you new up the Telepon it has both values in one property, which is what you see in the result. 因此,当您new Telepon时,它在一个属性中同时具有两个值,这就是您在结果中看到的。

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

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