MongoDB Flashcards
In MongoDB, how do you create a collection and add an item to that collection at the same time?
db.db_name.insertOne( {“test”: “test”} )
In MongoDB, how do you switch between DBs?
use db_name
In MongoDB, how do you delete a collection?
db.db_name.drop()
What is the difference between the native MongoDB driver for node and Mongoose?
mongoose holds the schemas within the application code, whereas the mongodb driver relies on the schemas set within the database
What is the syntax for creating a Mongoose item Schema?
const ItemSchema = new Schema({ field_name: field_type, required: true })
In Mongoose, how do you create a model?
Define the structure of the model and then export it to be received by other local files using:
module.exports = Item = mongoose.model(‘model_name’, ModelSchema)
In Mongoose, what is the syntax for posting a new item to MongoDB?
router.post('/path/to/api', (req, res) => { const newItem = new Item({ name: req.body.name });
newItem.save() .then(item => res.json(item) .catch(err => res.json({ message: err }); });
In Mongoose, what is the syntax for deleting an item from MongoDB?
router.delete(‘/path/to/api/:id’, (req, res) => {
const itemId = req.params.id;
Item.findById(itemId)
.then(item =>
item
.remove()
.then(() => res.json({ message: itemId }))
.catch(err =>
res.status(404).json({ message: err }));
});