修改記錄

修改記錄的方法

靜態(tài)方法:

  • update
  • findOneAndUpdate
  • findByIdAndUpdate

實(shí)例方法:

  • update
  • set and save

實(shí)例方法set and save

在test文件創(chuàng)建update_test.js:

const assert = require('assert');
const User = require('../src/user');

describe('Updating records', () => {
         let joe;
         
         beforeEach((done) => {
            joe = new User({name : 'Joe'});
            joe.save()
                .then(() => done());
         });
         
         it('instance type using set and save', () => {
            console.log(joe);
            joe.set('name', 'Alex');
            console.log(joe);
         });
});

再改變實(shí)例以后,要再次存進(jìn)數(shù)據(jù)庫(kù):

it('instance type using set and save', (done) => {
            joe.set('name', 'Alex');
            joe.save()
                .then(() => User.find({}))
                .then((users) => {
                      assert(users.length === 1);
                      assert(users[0].name === 'Alex');
                      done();
                });
         });

使用這個(gè)方法構(gòu)造的好處是,我們可以先修改實(shí)例的屬性,然后再存進(jìn)數(shù)據(jù)庫(kù),當(dāng)我們需要修改很多個(gè)屬性時(shí),只要與數(shù)據(jù)庫(kù)touch一次。


實(shí)例方法update

可以直接使用update函數(shù)來對(duì)數(shù)據(jù)庫(kù)記錄進(jìn)行更新:

joe.update({name: 'Alex'});

斷言函數(shù):
當(dāng)我們需要返回多個(gè)回調(diào)并且有多個(gè)斷言時(shí),可以寫一個(gè)斷言函數(shù)來減少代碼量:

function assertName(operation, done){  //js的函數(shù)作用域
            operation  //作為參數(shù)的函數(shù),讓它在斷言函數(shù)里返回promise
            .then(() => User.find({}))
            .then((users) => {
               assert(users.length === 1);
               assert(users[0].name === 'Alex');
               done();
            });
}

然后直接把函數(shù)作為參數(shù)使用:

assertName(joe.update({name: 'Alex'}), done);

所以it function變成:

it('A model instance can update', (done) => {
            assertName(joe.update({name: 'Alex'}), done);
});

靜態(tài)方法update

update(查找條件,更新內(nèi)容):

it('A model class can update', (done) => {
            assertName(User.update({name: 'Joe'}, {name: 'Alex'}), done);
});

靜態(tài)方法findOneAndUpdate

findOneAndUpdate(查找條件,更新內(nèi)容):

it('A model class can update one record', (done) => {
            assertName(User.findOneAndUpdate({name: 'Joe'}, {name: 'Alex'}), done);
});

靜態(tài)方法findByIdAndUpdate

findByIdAndUpdate(_id,更新內(nèi)容):

it('A model class can find a with an Id and update', (done) => {
            assertName(User.findByIdAndUpdate(joe._id, {name: 'Alex'}), done);
});
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容