修改記錄

修改記錄的方法

靜態方法:

  • update
  • findOneAndUpdate
  • findByIdAndUpdate

實例方法:

  • update
  • set and save

實例方法set and save

在test文件創建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);
         });
});

再改變實例以后,要再次存進數據庫:

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();
                });
         });

使用這個方法構造的好處是,我們可以先修改實例的屬性,然后再存進數據庫,當我們需要修改很多個屬性時,只要與數據庫touch一次。


實例方法update

可以直接使用update函數來對數據庫記錄進行更新:

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

斷言函數:
當我們需要返回多個回調并且有多個斷言時,可以寫一個斷言函數來減少代碼量:

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

然后直接把函數作為參數使用:

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

所以it function變成:

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

靜態方法update

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

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

靜態方法findOneAndUpdate

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

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

靜態方法findByIdAndUpdate

findByIdAndUpdate(_id,更新內容):

it('A model class can find a with an Id and update', (done) => {
            assertName(User.findByIdAndUpdate(joe._id, {name: 'Alex'}), done);
});
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容