最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

使用mongoose插入多个文档

IT培训 admin 2浏览 0评论

使用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时,它在一个属性中都有两个值,这就是你在结果中看到的。

使用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时,它在一个属性中都有两个值,这就是你在结果中看到的。

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论