์ฌ๋ฌ๋ถ, ์๋ ํ์ธ์,
๋ชฝ๊ตฌ์ค ๋ฒ์ 5.0.3๊ณผ ๋ ธ๋ ๋ฒ์ 9.4.0์ ์ฌ์ฉํ๊ณ ์์ต๋๋ค. ๋ชฝ๊ตฌ์ค ๋ฌธ์์ ๋ฐ๋ฅด๋ฉด model.create๋ ์์ฑ๋ ๋ฌธ์๊ฐ DB์ ์ ์ฅ๋ ๋ ํด๊ฒฐ๋๋ ์ฝ์์ ๋ฐํํด์ผ ํฉ๋๋ค. ๊ทธ๋ฌ๋ ์๋ ์ฝ๋์์ ๋ณผ ์ ์๋ฏ์ด ๋ฌธ์๊ฐ DB์ ์ ์ฅ๋๊ธฐ ์ ์ ์ฝ์์ด ํด๊ฒฐ๋ ๊ฒ์ฒ๋ผ ๋ณด์ ๋๋ค.
async function test(){
let schema = new mongoose.Schema({a: String});
let model = mongoose.model('test', schema);
await model.remove({}).exec();
await model.create({ a: 'test'},
(err,result)=> {console.log('created');});
await model.findOneAndUpdate(
{ a : 'test' } ,
{ a: 'newValue'}
)
.exec((err, result) => {
console.log('update : '+result);
});
await model.find({a: 'test'},(err,result) => {
console.log(result);
});
}
output in terminal :
update : null
found :
created
findOneAndUpdate๋ ๋ฌธ์๋ฅผ ์ฐพ์ง ๋ชปํ์ต๋๋ค. ๊ทธ ์ธ์๋ "created"๊ฐ ํฐ๋ฏธ๋ ๋์ ๋ํ๋๋ฏ๋ก await๊ฐ ๋น๋๊ธฐ ์์ 'create'๊ฐ ์๋ฃ๋ ๋๊น์ง ๊ธฐ๋ค๋ฆฌ์ง ์์ ๊ฒ์ฒ๋ผ create ๋ฉ์๋์ ์ฝ๋ฐฑ์ด ์คํ๋ฉ๋๋ค.
๊ทธ๋ฌ๋ ์๋์ ๊ฐ์ด create ์ฝ๋ฐฑ์ด ํธ๋ฆฌ๊ฑฐ๋๋ฉด ํด๊ฒฐ๋๋ promise๋ฅผ ์ถ๊ฐํ์ฌ ์์ํ ๊ฒฐ๊ณผ๋ฅผ ์ป์ต๋๋ค.
async function test(){
let schema = new mongoose.Schema({a: String});
let model = mongoose.model('test', schema);
await model.remove({}).exec();
await new Promise((resolve,reject) => {
model.create({ a: 'test'},
(err,result)=> {
console.log('created');
resolve();
});
});
await model.findOneAndUpdate(
{ a : 'test' } ,
{ a: 'newValue'}
)
.exec((err, result) => {
console.log('update : '+result);
});
await model.find({a: 'newValue'},(err,result) => {
console.log('found : ' +result);
});
}
output in terminal:
created
update : { _id: 5a735fbc1fe826233014d62d, a: 'test', __v: 0 }
found : { _id: 5a735fbc1fe826233014d62d, a: 'newValue', __v: 0 }
์ด์ ์ฐ๋ฆฌ๋ ์์ํ ๊ฒฐ๊ณผ๋ฅผ ์ป์์ต๋๋ค.
DB์์ ์๋ํ๋ ๋ชจ๋ ํจ์๋ ํด๊ฒฐ๋ ๊ฒฝ์ฐ ์์ , ํนํ ์ฟผ๋ฆฌ๊ฐ ์๋ฃ๋์์์ ๋ํ๋ด๋ ์ฝ์์ ๋ฐํํฉ๋๋ค. ์๋ฐํ ๋งํ๋ฉด ์ฟผ๋ฆฌ ๊ฐ์ฒด๋ฅผ ๋ฐํํ์ง๋ ์์ง๋ง model.create์ ๊ฒฝ์ฐ๋ ๋ง์ฐฌ๊ฐ์ง๋ผ๊ณ ๊ฐ์ ํฉ๋๋ค. ๋ํ DB์ ๋ฌธ์๊ฐ ์์ฑ๋์๋ค๋ ํ์๊ฐ ์๊ธฐ ๋๋ฌธ์ ์ดํ๋ ๋ฐํ๋ ์ฝ์์ด ๋ฌด์์ ์๋ฏธํ๋์ง ๊ถ๊ธํฉ๋๋ค. ์๋ง๋ ๋๋ ์ ์ฒด ์์ ์ ๋์ณค์ง๋ง ์ฝ๊ฐ ๋ชจํธํ๋ค๊ณ ์๊ฐํฉ๋๋ค.
4.x ๋ฌธ์์์ model.create์ ์ฝ๋ฐฑ์ ์ ๋ฌํ๋ฉด ์ฝ์์ ๋ฐํํ์ง ์๋๋ค๋ ๊ฒ์ ์ฝ์ ๊ฒ์ ๊ธฐ์ตํฉ๋๋ค.
let x = model.create({ a: 'test' }, () => {})
x.then(console.log(x)) //TypeError: Cannot read property 'then' of undefined
์ฝ๋ฐฑ์ ๊บผ๋ด๋ฉด:
let x = model.create({ a: 'test' })
x.then(console.log(x)) // Promise { <pending> }
model.js์ 5.x ์์ค๋ utils.promiseOrCallback์ ํธ์ถํ์ฌ ์ด๋ฅผ ๋ท๋ฐ์นจํฉ๋๋ค.
์, @lineus ๊ฐ ๋ง์ต๋๋ค. @CodeurSauvage ์ด ๋ฌธ์ ๋ฅผ
@CodeurSauvage @lineus ๊ฐ ๋ง์ต๋๋ค. mongoose 5๋ ์ฝ๋ฐฑ์ด ์ง์ ๋ ๊ฒฝ์ฐ ์ฝ์์ ๋ฐํํ์ง ์์ต๋๋ค . ๋ค์์ ๋์ฒดํ๋ฉด ์คํฌ๋ฆฝํธ๊ฐ ์๋ํฉ๋๋ค.
await model.create({ a: 'test'},
(err,result)=> {console.log('created');});
์ ํจ๊ป:
await model.create({ a: 'test'}).then(result => console.log('created'));
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
4.x ๋ฌธ์์์ model.create์ ์ฝ๋ฐฑ์ ์ ๋ฌํ๋ฉด ์ฝ์์ ๋ฐํํ์ง ์๋๋ค๋ ๊ฒ์ ์ฝ์ ๊ฒ์ ๊ธฐ์ตํฉ๋๋ค.
์ฝ๋ฐฑ์ ๊บผ๋ด๋ฉด:
model.js์ 5.x ์์ค๋ utils.promiseOrCallback์ ํธ์ถํ์ฌ ์ด๋ฅผ ๋ท๋ฐ์นจํฉ๋๋ค.