앞에서 Model을 정의하는 방법은 너무 많이 보다시피 정의된 스키마를 통해 모델을 생성하는 것이다. 이러한 모델에서 생성된 인스턴스를 Document라고 하는데 이 것은 다음 편에서 알아볼 예정이다.
const schema = new mongoose.Schema({name: 'string', size: 'string'});
cosnt Tank = mongoose.model('Tank', schema);
단순히 하나의 모델을 생성하기 위해서는 mongoose.model()
로 정의하면 된다.
const Tank = mongoose.model('Tank', schema);
const amll = new Tank({size: 'small'});
small.save(function(err) {
if (err) return handleError(err);
});
or
Tank.create({size: 'small'}, function (err, small) {
if (err) return handleError(err);
});
or
Tank.insertMany([{size: 'small'}], function(err) {
});
여기서 만약 모델 사용을 위한 연결이 되지 않으면 인스턴스 생성 및 제거가 되지 않기에 지속적으로 연결된 상태를 유지 해야 한다.
mongoose.connect('mongodb://localhost/gettingstarted');
or
const connection = mongoose.createConnection('mongodb://localhost:27017/test');
const Tank = connection.model('Tank', yourSchema);
Tank.find({size: 'small'}).where('createdDate').gt(oneYearAgo).exec(callback);
Tank.deletOne({size: 'large'}, function (err) {
if (err) return handleError(err);
});
Tank.updateOne({size: 'large'}, {name: 'T-90'}, function(err, res) {
})
우리가 DB를 지속적으로 가져와 업데이트 하고 소통하는 방식을 Change Stream이라 하고 이 방식은 MongoDB Replica set로 연결되지 않았을 때는 사용할 수 없다.
async function run() {
const personSchema = new mongoose.Schema({
name: String
});
const Person = mongoose.model('Person', personSchema);
Person.watch().on('change', data => console.log(new Date(), data));
console.log(new Date(), 'Inserting doc');
await Person.create({name: 'Axl Rose'});
}