我刚刚开始使用Mongoose和MongoDB。我已经在stackoverflow上尝试了所有我能找到的东西,然而,由于我不知道问题是什么,我迷失了。
我有以下2个模型,它们位于2个不同的文件中:
var UserSchema = require('mongoose').model('User').schema;
var tournamentSchema = mongoose.Schema({
tournamentName: String,
nrOfPlayers: String,
players: [{ type: mongoose.Schema.Types.ObjectId, ref: UserSchema }],
openForLeagues: {
leagues: []
},
edition: String,
description: String,
startDate: Date,
endDate: Date,
startHour: String,
prize: Boolean,
sponsors: String,
ingameChatChannel: String,
twitchStreamChannel: String
});
module.exports = mongoose.model('Tournament', tournamentSchema);
var userSchema = mongoose.Schema({
local: {
nickname: String,
battlenetid: String,
email: String,
password: String,
race: String,
league: String,
role: String,
website: String
}
});
module.exports = mongoose.model('User', userSchema);
在我的routes.js文件中,我执行以下操作:
app.post('/signup-tournament/:_id/:userId', isLoggedIn, function(req, res) {
var playerId = req.params.userId;
var nickname = req.user.local.nickname;
console.log(ObjectId.isValid(req.params.userId)); //true
console.log(ObjectId.isValid(req.params._id)); //true
if (ObjectId.isValid(playerId) && ObjectId.isValid(req.params._id)) {
Tournament.findByIdAndUpdate(req.params._id, {
$pushAll: {
players: {
values: [playerId, nickname]
}
}
}, function(err, tournament) {
if (err)
res.send(err)
else
res.redirect('/signup-tournament/' + req.params._id + req.params.userId);
});
}
});
当我发帖时,我收到以下错误:
{
"message": "Cast to ObjectId failed for value \"[object Object]\" at path \"players\"",
"name": "CastError",
"type": "ObjectId",
"value": [{
"values": ["53e340b3afb9657f0dbcf994", "cristidrincu"]
}],
"path": "players"
}
我不明白为什么使用ObjectId.isValid()验证ID时会出现强制转换错误...我花了2天试图自己解决这个问题,所以请帮忙:)谢谢!
答案 0 :(得分:3)
您正在尝试执行针对findByIdAndUpdate
的{{1}}操作。问题出现在以下代码中:
tournamentSchema
Tournament.findByIdAndUpdate(req.params._id, {
$pushAll: {
players: {
values: [playerId, nickname]
}
}
})
应包含players
个对象,因此它应该是播放器User
(十六进制_id
或String
)或有效{带有ObjectId
字段的{1}}对象。
但您尝试推送无效对象User
。
以下是此操作的外观:
_id
NB 不确定{ values: [playerId, nickname] }
在您的示例中的含义,但它看起来不是有效的Tournament.findByIdAndUpdate(req.params._id, {
$pushAll: {
players: [playerId]
}
})
,因此我删除了它。