본문 바로가기
창고 3/[Dev] My Readme

몽고 DB 기초 3

by 부엉이의 정보 창고 2022. 1. 6.
728x90

CRUD in MongoDB

Inserting, searching, updating, and deleting are asynchronous actions in database. The 'done' callback function should be called once the asynchronous operations are done.

// done callback convention in Node.js
const doSomething = function (done) { 
    if (err) return done(err)
    done(null, result)
}

Types of Mongoose CRUD methods are as follows(cb : short for callback) :

  • mongoose.Schema
  • mongoose.model
  • document.save
  • model.find(filter, cb) : find all matches
  • model.findOne(filter, cb) : find one match
  • model.findById(filter, cb)
  • model.findAndUpdate(filter, update, new) : set the third argument 'new'. Otherwise it will return unchanged object by default
  • model.findByIdAndRemove(filter, cb)
  • model.remove : delete all matches. returns JSON object, not updated(meaning some records deleted) docs.
  • chain search : making query chains to narrow results.
// query chain search in MongoDB
const queryChain = (done) => { 
    const myKeyword = "sushi"
    Sushi.find(myKeyword)
         .sort( { price : 1 } ) // show expensive sushi first
         .limit(5) // show 5 of them 
         .select( { location : 1} ) // show location 
         .exec(function(err, data) {
             if (err) return console.log(err)
             done(null, data)
         }) // execute queries. If exec method is not provided with the callback, it won't work. 
}

Creating And Saving records

You can create model and save the document(model instance) in database, which is the purpose of creating it.

// Create a model from schema
let Person = mongoose.model('Person', personSchema);

const createAndSavePerson = (done) => {
  // Create a document(model instance)
  const person = new Person( {
    name : "Jake Sung", 
    age : 27, 
    favoriteFoods : ["Pizza, Sushi"]
   })

   // Save the document in database
   person.save(function(err, data) { 
    if (err) return console.log(err)
    done(null, data);
   })
};

Document is stored in database

When saving a document, MongoDB creates a field called "_id", which is a unqiue alphanumeric(letter + number) key. Searching records by _id is super common operation in MongoDB.

Finding records

  • find(condition) : find multiple records matched with the conditions
  • findOne(condition) : find the first record matched with the condition

Object ID

Once model instance is saved in the database, how do we know which one is which if the name is all the same? Finding a specific record is done with object id since each record in database has a different object id.

Deleting records

  • model(instance).remove
  • model(whole collections).remove
  • model.findOneAndRemove
    1. Create and save a new record
    1. Use findOneAndRemove to remove the record
    1. Use findOne to check if the removed record exists. It should be null if deleted.

Updating records

  • model(instance).update
  • model(whole collections).update
myModel.update({}, {$inc : { weight : 1 } }) // update whole collections, increasing weight property by 1 
  • model.findOneAndUpdate
    1. Create a save a new record
    1. Use findOneAndUpdate to update the record
    1. Use findOne to check the updated record. Its value should be changed.
728x90

'창고 3 > [Dev] My Readme' 카테고리의 다른 글

몽고 DB 기초 5  (0) 2022.01.10
몽고 DB 기초 4  (0) 2022.01.07
몽고 DB 기초 2  (0) 2022.01.05
몽고 DB 기초 1  (0) 2022.01.04
git commit 취소하는 법, git push 취소하는 법, git 폴더명 변경하기  (0) 2022.01.04

댓글


loading