我在创建这条特定的路线时遇到了麻烦 . 我正在尝试将新的媒体对象发布到媒体数组中,但我的所有代码都将ObjectId保存到数据库而不是保存newMedia对象 . 我在Postman中测试了它,结果如下:
AthleteProfile.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const AthleteSchema = new Schema({
athEmail: String,
firstName: {
type: String,
validate: {
validator: (firstName) => firstName.length > 2,
message: 'Name must be longer than 2 characters.'
}
},
lastName: {
type: String,
validate: {
validator: (lastName) => lastName.length > 2,
message: 'Name must be longer than 2 characters.'
}
},
profilePic: String,
accountType: String,
events: [{
ref: 'Event',
type: Schema.Types.ObjectId
}],
media: [{
ref: 'Media',
type: Schema.Types.ObjectId
}],
height: String,
weight: Number,
birthday: Date,
sports: [{
ref: 'Sport',
type: Schema.Types.ObjectId
}]
gradYear: Number,
school: String
});
module.exports = AthleteSchema;
Media.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const MediaSchema = new Schema({
id: Schema.Types.ObjectId,
title: String,
createdTimestamp: Date,
mediaTimestamp: Date,
videoUrlEnd: String,
description: String
});
const Media = mongoose.model('Media', MediaSchema);
module.exports = Media;
route.js
const mongoose = require('mongoose');
const User = require('../models/User');
const Media = require('../models/Media');
exports.postMedia = async (req, res) => {
const { clientKey } = req.params;
if (clientKey !== config.clientKey) {
res.send({ message: 'You do not have the correct client key to access
this database.'})
} else {
const { id } = req.query;
const {
title,
description,
videoUrlEnd
} = req.body;
let newMedia = new Media({
_id: mongoose.Types.ObjectId(),
title: title,
description: description,
createdTimestamp: Date.now(),
mediaTimestamp: Date.now(),
videoUrlEnd: videoUrlEnd
});
console.log(newMedia);
try {
let user = await User.findByIdAndUpdate({ _id: id },
{ $push: { 'athleteProfile[0].media': newMedia } },
{new: true});
if (!user) {
return res.status(404).send(new MyError('Not Found Error', ['User
for user id ' + id + ' and user id '+ id + ' not found']));
} else {
res.status(200).send(user);
}
} catch (err) {
if (err.name === 'MongoError' && err.code === 11000) {
res.status(409).send(new MyError('Duplicate key', [err.message]));
}
res.status(500).send(new MyError('Unknown Server Error', ['Unknow
server error when updating user for user id ' + id + ' and user id
'+ id]));
}
}
}
我更新了route.js文件,如果它只是一个id,它就会停止将它保存到数据库中 . 我尝试发送请求后,我的console.log看起来像这样 .
[0] App listening on port: 5000
[0] { _id: 5adf651e410ce10b9024c2bb,
[0] title: 'This is a title',
[0] description: 'This is a description',
[0] createdTimestamp: 2018-04-24T17:10:54.055Z,
[0] mediaTimestamp: 2018-04-24T17:10:54.055Z,
[0] videoUrlEnd:
'http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4' }
我很感激你解决这个问题的任何帮助 . 我真的被卡住了为什么它不起作用 . 我在SubDocuments上使用mongoose文档尝试了很多变化,但它仍然无法正常工作 .
更新:此编辑的代码不再将ObjectId保存到数据库 . 我不知道这是否有进展 . 更新了图片以显示整个用户结构 .