我用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
我想要这样的收藏结果:
(示例)
任何帮助和建议将不胜感激
谢谢!
答案 0 :(得分:0)
1)每次.save
调用只会影响一个文档,请检出insertMany
来处理多个文档。
2)req.body.telepon
是数字数组,或者已经是逗号分隔的数字列表;如果它是一个数组,则.toString
仍将以逗号分隔列表。因此,new
在Telepon上时,它在一个属性中同时具有两个值,这就是您在结果中看到的。