**EDIT: Wow my mistake. I forgot to subtract (-1) from the array.length to get the last item in the array. Rookie mistake!
I'm using an Express server to save data to my MongoDB database. I have one route set up that accepts an object with the following information:
{ handle: "twitterHandle" }
That information is saved based on my schema, here:
const TwitterSchema = new mongoose.Schema({
handle: {
type: String,
required: true
}
});
Which is stored inside of my user schema, here:
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
trim: true,
minLength: 1,
unique: true,
validate: {
validator: (value) => {
return validator.isEmail(value);
},
message: '{VALUE} is not a valid email'
}
}
trackers: {
tweets: {
type: [TwitterSchema], // SUBDOCUMENT IS LOCATED HERE
default: null
},
legislation: {
type: [LegislationSchema],
default: null
},
court_cases: {
type: [CourtCaseSchema],
default: null
}
}
});
After saving the tweet via a PUSH request to a route on my server, I would like to return the newly saved tweet data, which would be a JSON object with the tweet handle and the _id property, which is generated by MongoDB.
However, I'm not able to access the last item in the tweets subdocument. How do I do that?
Here's the route, /api/users/me/trackers/tweets
that handles POST requests to my backend for twitter data:
const post_tweet = (req,res) => {
User.findOne({_id: "5b7ef883c69aac4cf99acb89"}) // hard coded ID value for now...
.then((user) => {
user.trackers.tweets.push(req.body);
return user.save();
})
.then((user) => {
res.status(200)
.send(user.trackers.tweets[SOMEHOW GET LAST TWEET?])
})
.catch((e) => {
console.log("Request failed.")
res.status(400).send(e);
});
}