【问题标题】:Insert multiple document with mongoose使用猫鼬插入多个文档
【发布时间】:2019-02-24 04:20:48
【问题描述】:

我使用 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

我想要这样的收藏结果:

(示例)

任何帮助和建议将不胜感激

谢谢!

【问题讨论】:

  • 通常我制作一个控制器并使用 express 的路由器并导出路由器。如果你这样做,你可以使用insertMany()。您也许可以按照自己的方式进行设置,但我从来没有这样设置过。

标签: node.js mongodb express mongoose


【解决方案1】:

1) 每个.save 调用只会影响一个文档,请查看insertMany 以执行多个。

2) req.body.telepon 要么是一个数字数组,要么已经是逗号分隔的数字列表;如果它是一个数组,.toString 无论如何都会产生一个逗号分隔的列表。因此,当您在 Telepon 上 new 时,它在一个属性中具有两个值,这就是您在结果中看到的。

【讨论】:

    猜你喜欢
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 2017-01-29
    • 1970-01-01
    • 2019-01-22
    • 2015-06-26
    • 2015-09-06
    相关资源
    最近更新 更多