node.js - Cast to ObjectId failed for value \"[object Object]\" at path \"players\" -
i'm starting out mongoose , mongodb. i've tried find here on stackoverflow, however, i'm lost not know problem is.
i have following 2 models, reside in 2 different files:
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);
inside routes.js file, following:
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); }); } });
when post, following error:
{ "message": "cast objectid failed value \"[object object]\" @ path \"players\"", "name": "casterror", "type": "objectid", "value": [{ "values": ["53e340b3afb9657f0dbcf994", "cristidrincu"] }], "path": "players" }
i not understand why there cast error when ids validated using objectid.isvalid()... i've spent 2 days trying figure on own, please :) thank you!
you're trying perform findbyidandupdate
operation against tournamentschema
. problem in following code:
tournament.findbyidandupdate(req.params._id, { $pushall: { players: { values: [playerid, nickname] } } })
players
should contain user
objects, should either player's _id
(hex string
or objectid
), or valid user
object _id
field.
but you're trying push invalid object { values: [playerid, nickname] }
instead.
here how operation should look:
tournament.findbyidandupdate(req.params._id, { $pushall: { players: [playerid] } })
n.b. not sure nickname
mean in example, doesn't valid objectid
, removed it.
Comments
Post a Comment