Node.js+MongoDB中存储字符串数组失败问题求助
问题:MongoDB无法存储字符串数组类型的jobType字段
我找过类似问题但没找到解决办法,现在开发一款职位发布应用,每个职位对应多种类型,需要存储字符串数组类型的jobType字段。
职位模型代码
const mongoose = require("mongoose"); const postSchema = mongoose.Schema({ content: { type: String, required: true }, imagePath: { type: String, required: true }, state: { type: String, required: true }, substate: { type: String, required: true }, address: { type: String, required: true }, jobType: { type: [String] }, creator: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true } }); module.exports = mongoose.model("Job", postSchema);
存储数据的API代码
我能100%确认数据已正确传到API,req.body.jobtype是字符串格式,尝试用JSON.parse转成数组但没用,MongoDB里只存了空数组:
const Job = require("../models/job"); exports.createJob = (req, res, next) => { console.log('create job api hit') const url = req.protocol + "://" + req.get("host"); const post = new Job({ content: req.body.content, imagePath: url + "/images/" + req.file.filename, creator: req.userData.userId, state: 'new', substate: 'new', address: req.body.address, jobtype: JSON.parse(req.body.jobtype) // 无法正确存储 }); post .save() .then(createdJob => { res.status(201).json({ message: "Job added successfully", post: { ...createdJob, 'pecker':'pecker hecks out', id: createdJob._id } }); }) .catch(error => { res.status(500).json({ message: JSON.stringify(error) }); }); };
解决方案
核心问题:字段名大小写不匹配
模型里定义的字段是jobType(驼峰命名),但API里赋值的是jobtype(全小写),Mongoose会忽略不匹配的字段,这就是jobType一直为空数组的原因。修正代码
把API里的jobtype改成jobType:
const post = new Job({ // ...其他字段 jobType: JSON.parse(req.body.jobtype) });
- 适配不同输入格式
如果前端传的不是合法JSON数组字符串(比如是"全职,兼职"这种逗号分隔的字符串),改用split分割:
jobType: req.body.jobtype.split(',')
- 调试验证
加日志打印解析后的结果,确认数据格式正确:
console.log("解析后的jobType:", JSON.parse(req.body.jobtype));
内容的提问来源于stack exchange,提问作者user17281101
相关产品推荐
相关产品推荐

