I am trying to link two tables in mongo db. I have a User table where user has an _id. And a News table where the columns should be _id(for the news) and the userId (to link news to a user).
The way my api works, is the userID gets appended to req variable when the request goes through authentication.
This is the model for User
const mongoose = require("mongoose");
const User = mongoose.model(
"User",
new mongoose.Schema({
name: String,
surname: String,
email: String,
password: String,
admin: Boolean,
profileImage: String,
})
);
And this is a model for News
const mongoose = require("mongoose");
const News = mongoose.model(
"News",
new mongoose.Schema({
userID: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
})
);
and this is the snippet for saving a new news record:
upload = (req, res) => {
const news = new News({
userId: mongoose.Types.ObjectId(req.userId)
})
//at this point userID in news is UNDEFINED for some reason. req.userId is not undefined.
news.save((err)=>{
if (err) {
res.status(500).send({ message: err + "NewsError" });
return;
}
})
}
Ideally this should end with a new row appearing in the table in the database, but only the auto generated _id appears, and no userID
No UserID column
2
Answers
I found the error:), Where I define the model. userID is spelled with capital ID, but where I assign the variable its written as userId. I am just blind. Thanks for everyones help.
Maybe instead of
mongoose.Types.ObjectId(req.userId)
you can instead use this code: