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