Mongoose - MongoDB Flashcards

1
Q

What’s an ODM?

A

Object Document Mapper - It allows the ODM - which accepts the Javascript and translate it to MongoDB script and simplifies working with Database in Nodejs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Initiate Moongoose

A

npm install mongoose

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Connect to a Collection

A

mongoose.connect( ‘mongodb://localhost:27017/collection_name’ , {useNewUrlParser: true} );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Schema and Start a collection

A

Schema is the model on which a new collection will be based on.

const itemSchema = new mongoose.Schema( {
                                     var1: datatype here,
                                     var2: datatype here,
                                     ...
                                     });
const Item = mongoose.model( 'Item' , itemSchema );  
  // Anything in place of 'Item' should always be singular and collection will be saved in plural automatically.

const item1 = new Item( { var1: 2, var2: “great” …. } );

item1.save( );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Insert into the collections

A

//initialise the schema

const varx = new Model_name ( {
                               var1: 3,
                               var2: "hello"
                               } );
const vary = new Model_name ( {
                               var1: 3,
                               var2: "hello"
                               } );

Item.insertMany( [varx, vary], function (err) {
if(!err) { // log ‘great’ }
} );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Read and Find in a Collection

A

Model.find ( function(err, collection_name) {
if( !err )
{
console.log(collection_name);
}
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Validation of data being input

A

There are built in validator in mongoose to aid in validation.

Validation like min, max for Number data type.

enum validation is used to narrow down among selected string or number.

for example in Schema initialize -
const itemSchema = new mongoose.Schema ( {
var1: {
type: Number,
min: 1,
max: 10 } ); // => This schema verifies that var1 stays in between 1 and 10 including 1 and 10.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Required Validation

A

the required: [ true, “comment here”] makes sure that a data field has been input by user.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Update and Delete a field in collection

A

Model.updateOne( {query here} , {set field here just like writing json} , function(err) { log if error or successful} );

Model.deleteOne( {query here} , function(err) { log if error or successful} );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly