I have two schemas, defined as following:
我有两个模式,定义如下:
var userSchema = new Schema({
email: String,
name: String,
role: String,
password: String
})
var raceSchema = new Schema({
date: Date,
name: String,
location: String,
time: String,
register: String,
participants: [{ type: Schema.Types.ObjectId, ref: 'User'}],
registered_participants: [{ type: Schema.Types.ObjectId, ref: 'User'}],
})
As you can see, I reference the first schema twice in the second schema. If I add a reference to a user in one of the lists, everything is fine. But when I add a reference to the same user to the other list I get the following error: Cast to [undefined] failed for value
如您所见,我在第二个模式中引用了第一个模式两次。如果我在其中一个列表中添加对用户的引用,一切都很好。但是当我将同一用户的引用添加到另一个列表时,我收到以下错误:转换为[undefined]失败的值
What causes this error? Is it related to the fact that the same schema is used twice in the second schema?
是什么导致这个错误?是否与在第二个模式中使用相同模式两次的事实有关?
Edit: I get the error when I call the following Express endpoint:
编辑:当我调用以下Express端点时出现错误:
app.post('/race/:id/registered', passport.authenticate('jwt', { session: false}), (req, res) =>
Race.findOne({ _id: req.params.id }, function (err, race) {
if (err) return res.json({'Error': err})
if (!race) return res.json({'Error': 'Race not found'})
race.registered_participants.push(req.user)
race.save(function (err, updatedRace) {
if (err) return res.json({'Error': err})
res.send(updatedRace)
})
})
)
Edit 2: The model definitions:
编辑2:模型定义:
var User = mongoose.model('User', userSchema);
var Race = mongoose.model('Race', raceSchema);
1 个解决方案
#1
0
Try using findByIdAndUpdate
in your POST
method instead:
请尝试在POST方法中使用findByIdAndUpdate:
app.post('/race/:id/registered', passport.authenticate('jwt', { session: false}), (req, res) =>
Race.findByIdAndUpdate(req.params.id,
{ $push: { registered_participants: req.user } },
function (err, race) {
if (err) return res.json({'Error': err})
res.send(race)
})
)
#1
0
Try using findByIdAndUpdate
in your POST
method instead:
请尝试在POST方法中使用findByIdAndUpdate:
app.post('/race/:id/registered', passport.authenticate('jwt', { session: false}), (req, res) =>
Race.findByIdAndUpdate(req.params.id,
{ $push: { registered_participants: req.user } },
function (err, race) {
if (err) return res.json({'Error': err})
res.send(race)
})
)