Recently, I embarked on the journey of developing an app for my senior project that necessitates the integration of a database. After careful consideration, I opted for Mongoose due to its noSQL nature and relatively easier learning curve.
However, as progress continued, I encountered a roadblock - I couldn't quite grasp how to modify an existing Schema and incorporate new keys into it.
Take, for instance, this Schema which mirrors a post (think Tweets or Facebook updates) containing:
- A string representing the content of the post
- The user's ID who created the post
- The date when the post was made
My current code snippet entails:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const PostsSchema = new Schema({
Value: {
type: String,
required: true
},
User: {
type: Schema.Types.ObjectId,
ref:'users'
},
Date: {
type: Date,
default: Date.now
}
});
// Establish collection and append schema
mongoose.model('posts', PostsSchema, 'posts');
What I aim to achieve now is to somehow access that schema and introduce a new key using a syntax akin to
PostsSchema.add({Private: { default: false}});
This implies that the schema in the database will appear as follows:
{
"_id": {
"$oid": "1831g98af21n9s5u7s9ccchj5"
},
"Value": "Beautiful day outside, can't wait to go jogging!",
"User": {
"$oid": "9a79ab143lbk9lk55wq327oi3226m"
},
"Date": {
"$date": "2018-10-29T01:28:44.408Z"
},
"Private": "false"
"__v": 0
}
To circle back to my query - is there any way to accomplish this task? Alternatively, if you could point me towards documentation outlining similar methods, I would be extremely grateful. Thank you immensely!