I am creating a webAPI on chesstournaments. I am writing that in C# (.NET7) using MongoDB Entity Framework. The problem I have is the following:
When inserting a tournament with the reference to a user the MongoDB creates ObjectId('000000000000000000000000') instead of the actual reference to the user.
Here is my TournamentModel.cs:
public enum TournamentStatus
{
Planned,
Ongoing,
Finished,
}
public enum TournamentType
{
Classic,
Rapid,
Blitz,
Bullet
}
[Collection("tournaments")]
public class Tournament
{
public ObjectId Id { get; set; }
public ObjectId? UserId { get; set; }
[Required(ErrorMessage ="Title is required")]
public string Title { get; set; }
public string EventUrl { get; set; }
public string County { get; set; }
[Required(ErrorMessage = "Status is required")]
public TournamentStatus Status { get; set; }
[Required(ErrorMessage ="Provide type of tournament")]
public TournamentType Type { get; set; }
[Required(ErrorMessage = "Provide information whether the tournament is FIDE classified")]
public Boolean IsFide { get; set; }
[Required(ErrorMessage ="Provide details for tournament")]
public TournamentDetails Details { get; set; }
}
Here is Adding logic in TournamentService.cs:
public void AddTournament(Tournament newTournament)
{
_BCAContextDb.Tournaments.Add(newTournament);
_BCAContextDb.ChangeTracker.DetectChanges();
Console.WriteLine(_BCAContextDb.ChangeTracker.DebugView.LongView);
_BCAContextDb.SaveChanges();
}
And here is my Posting logic in TournamentController.cs:
[HttpPost]
public ActionResult<Tournament> PostTournament(Tournament tournament)
{
_tournamentService.AddTournament(tournament);
return CreatedAtAction(nameof(GetTournamentById), new { id = tournament.Id }, tournament);
}
Now this is my typescript script that's supposed to shove in a new tournament with a reference to a user:
const agent = new https.Agent({
rejectUnauthorized: false,
});
let tournament = {
userId:{},
title: "string",
eventUrl: "string",
county: "string",
status: 0,
type: 0,
isFide: true,
details: {
startDate: "2024-03-13T18:53:41.465Z",
endDate: "2024-03-13T18:53:41.465Z",
place: "string",
gameTempo: "string",
referee: "string",
organizer: "string",
roundsTotal: 0,
roundsEnded: 0,
gameSystem: "string",
},
};
const grabData = async () => {
try {
const response = await axios.get("https://localhost:7001/api/user", { httpsAgent: agent });
const id = response.data[0].id;
console.log(id);
return id;
} catch (error) {
console.error("Error:", error.message);
throw error;
}
};
const main = async () => {
try {
const userId = await grabData();
tournament.userId = userId;
const tournamentToPush = tournament;
console.log("Tournament pushed:", tournamentToPush);
const response = await axios.post("https://localhost:7001/api/tournament", tournamentToPush, { httpsAgent: agent });
console.log("Tournament created:", response.data);
} catch (error) {
console.error("Error:", error.message);
}
};
main();
Now the part that I don't understand is that console.log("Tournament pushed:", tournamentToPush); logs out properly:
Tournament pushed: {
userId: {
timestamp: 1710351938,
machine: 1666371,
pid: -758,
increment: 3116068,
creationTime: '2024-03-13T17:45:38Z'
},
title: 'string',
eventUrl: 'string',
county: 'string',
status: 0,
type: 0,
isFide: true,
details: {...}
}
However the document in database looks like this:
and I have no clue what did I do wrong. All answers and tips are appreciated.

You need to specify an id field for the model to have it auto populate as a new Object Id.
This can be done using the following attribute:
BsonIdAttributeIE:
[BsonId] public string Id