[英]How to save an array of strings in mongodb
我發現了一些關於堆棧溢出的類似問題,例如: How to save array of Strings in Node Mongodb Mongoose - Save array of strings
但我不知道為什么我的方法不起作用
我正在嘗試保存數組字符串“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);
這是用於在 MongoDB 上保存數據的 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) // 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)
});
});
};
你打錯了。 在您的模型中,您定義jobType
屬性,但是在保存數據時,您將其作為jobtype
傳遞。
所以,而不是這個:
jobtype: JSON.parse(req.body.jobtype)
做這個:
jobType: JSON.parse(req.body.jobtype)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.