繁体   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