I have a user and a message model. The relation is the following: a user can have many messages.
Goal: I'm looking for the best or most elegant way of adding a new message and link it to the corresponding user.
User model:
const UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
register_date: {
type: Date,
default: Date.now
},
osrs_messages: [OsrsMessage]
});
Message model:
const OsrsMessageSchema = new Schema({
message: {
type: String,
required: true,
},
username: {
type: String,
required: true,
unique: true,
},
send_date: {
type: Date,
default: Date.now
}
});
My router that adds a new message and adds the message to the user in question:
router.post("/osrs", verifyAccessToken, async (req, res) => {
try {
const { username, message } = req.body;
// create a new message and save
let newMessage = new OsrsMessage({ username, message });
newMessage = await newMessage.save();
// get the associated user and add new message to messages array
let user = await User.findById(req.user.id);
user.osrs_messages.push({ username, message });
user = await user.save();
return res.status(200).json({ message: "message received" });
} catch (error) {
console.log("error message:", error);
return res
.status(500)
.json({ message: "Oops... looks like something went wrong" });
}
});
Are there any ways I can improve this? Should I use findOneAndUpdate or insert instead? Can I add a message automatically to my message collection if I link it to a user or do I always have to manually add it to the collection?