I have found a few similar questions on stack overflow like this one: How to save array of Strings in Node Mongodb Mongoose - Save array of strings
but I cant figure out why my method is not working
I am trying to save the string of arrays "jobType". context: I am creating an app where people can post jobs. each job can have multiple types.
here is my job model::
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);
this is the API used to save the data on MongoDB: I am 100% sure that the data is getting to the API correctly. the parameter "req.body.jobtype" contains all the info as a string. I am trying to use JSON.parse to change the string into an array but its not working. when I check MongoDB, an empty array is being stored
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) // fix: not storing correctly
});
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)
});
});
};
CodePudding user response:
You have a typo. In your model, you defined jobType
property, but when saving the data, you are passing it as jobtype
.
So, instead of this:
jobtype: JSON.parse(req.body.jobtype)
Do this:
jobType: JSON.parse(req.body.jobtype)