【发布时间】:2020-03-12 12:12:28
【问题描述】:
我正在尝试在邮递员中插入一个 ObjectId,在 Content-Type 的标头中,我使用 multipart/form-data
并不断收到错误
{
"errors": {
"singer": {
"message": "Cast to ObjectID failed for value \"ObjectId(\"5dcf8dc320742961c8b5a801\")\" at path \"singer\"",
"name": "CastError",
"stringValue": "\"ObjectId(\"5dcf8dc320742961c8b5a801\")\"",
"kind": "ObjectID",
"value": "ObjectId(\"5dcf8dc320742961c8b5a801\")",
"path": "singer",
"reason": {
"message": "Cast to ObjectId failed for value \"ObjectId(\"5dcf8dc320742961c8b5a801\")\" at path \"singer\"",
"name": "CastError",
"stringValue": "\"ObjectId(\"5dcf8dc320742961c8b5a801\")\"",
"kind": "ObjectId",
"value": "ObjectId(\"5dcf8dc320742961c8b5a801\")",
"path": "singer"
}
}
},
"_message": "Song validation failed",
"message": "Song validation failed: singer: Cast to ObjectID failed for value \"ObjectId(\"5dcf8dc320742961c8b5a801\")\" at path \"singer\"",
"name": "ValidationError"
}
这是我的路线代码,并在歌手字段中将 ObjectId 作为 req.body 传递
router.post('/addSoloSong', mp3.single('mp3File'), async (req, res) => {
console.log(req.file)
console.log(req.body.singer);
const newSong = new Song({
title: req.body.title,
singer: req.body.singer,
releaseDate: Date.parse(req.body.releaseDate),
mp3File: req.file.path,
createdAt: new Date()
})
try {
let songAdded = await newSong.save()
res.status(201).json(songAdded)
} catch (err) {
console.log(err);
res.status(400).json(err)
}
})
并将歌手字段创建为 ObjectId
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const songSchema = new Schema({
title: {
type: String,
required: true
},
singer: {
type: Schema.Types.ObjectId,
ref: "Singer",
required: true
},
featureSinger: {
type: Schema.Types.ObjectId,
ref: "Singer"
},
groupBand: {
type: Schema.Types.ObjectId,
ref: 'GroupBand'
},
releaseDate: {
type: Date,
required: true
},
mp3File: {
type: String,
required: true,
ref: "/public/mp3"
},
createdAt: {
type: Date,
default: null
},
updatedAt: {
type: Date,
default: null
},
deletedAt: {
type: Date,
default: null
},
assignedAt: {
type: Date,
default: null
}
});
const Song = mongoose.model("Song", songSchema);
module.exports = Song;
我想在将 ObjectId 插入表单数据时传递它,我错过了什么? 我也想问一下邮递员的mp3File,它说,文件不在你的工作目录中?这是什么意思?
【问题讨论】: