https://mongoosejs.com/docs/5.x/docs/guide.html
상상 그 이상의 날것
index.js
// mongoose
// const mongoose = require('mongoose');
// main().catch(err => console.log(err));
// async function main() {
// await mongoose.connect('mongodb://localhost:27017/movieApp');
// // use `await mongoose.connect('mongodb://user:password@localhost:27017/test');` if your database has auth enabled
// }
const mongoose = require('mongoose');
mongoose
.connect('mongodb://localhost:27017/movieApp', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('CONNECTION OPEN!!!');
})
.catch((err) => {
console.log('OH NO ERROR!!!');
console.log(err);
});
// const db = mongoose.connection;
// db.on('error', console.error.bind(console, 'connection error:'));
// db.once('open', function () {
// // we're connected!
// console.log('CONNECTION OPEN!!!');
// });
const movieSchema = new mongoose.Schema({
title: String,
year: Number,
score: Number,
rating: String,
});
const Movie = mongoose.model('Movie', movieSchema);
// const amadeus = new Movie({
// title: 'Amadeus',
// year: 1986,
// score: 9.2,
// rating: 'R',
// });
// Movie.insertMany([
// { title: 'Amelie', year: 2001, score: 8.3, rating: 'R' },
// { title: 'Alien', year: 1979, score: 8.1, rating: 'R' },
// { title: 'The Iron Giant', year: 1999, score: 7.5, rating: 'PG' },
// { title: 'Stan By Me', year: 1986, score: 8.6, rating: 'R' },
// { title: 'Moonrise Kingdom', year: 2012, score: 7.6, rating: 'PG-13' },
// ]).then((data) => {
// console.log('IT WORKED!');
// console.log(data);
// });
terminal:
> amadeus.save()
Promise {
<pending>,
[Symbol(async_id_symbol)]: 585,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
}
> amadeus
{
title: 'Amadeus',
year: 1986,
score: 9.2,
rating: 'R',
_id: new ObjectId("6360bc1372e2ac921a72e2d8"),
__v: 0
}
> amadeus.save()
Promise {
<pending>,
[Symbol(async_id_symbol)]: 771,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
}
>
(To exit, press Ctrl+C again or Ctrl+D or type .exit)
>
yeji@Yejiui-MacBookAir codeit % node
Welcome to Node.js v16.15.1.
Type ".help" for more information.
> .load index.js
> CONNECTION OPEN!!!
amadeus
{
title: 'Amadeus',
year: 1986,
score: 9.2,
rating: 'R',
_id: new ObjectId("6360bee2e3a860c8d3eb165e")
}
> amadeus
{
title: 'Amadeus',
year: 1986,
score: 9.2,
rating: 'R',
_id: new ObjectId("6360bee2e3a860c8d3eb165e")
}
> amadeus.save()
Promise {
<pending>,
[Symbol(async_id_symbol)]: 368,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
}
> amadeus.score = 9.5
9.5
> amadeus.save()
Promise {
<pending>,
[Symbol(async_id_symbol)]: 537,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
}
>
(To exit, press Ctrl+C again or Ctrl+D or type .exit)
>
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
IT WORKED!
[
{
title: 'Amelie',
year: 2001,
score: 8.3,
rating: 'R',
_id: new ObjectId("6360ec50077f2f2ccc65b307"),
__v: 0
},
{
title: 'Alien',
year: 1979,
score: 8.1,
rating: 'R',
_id: new ObjectId("6360ec50077f2f2ccc65b308"),
__v: 0
},
{
title: 'The Iron Giant',
year: 1999,
score: 7.5,
rating: 'PG',
_id: new ObjectId("6360ec50077f2f2ccc65b309"),
__v: 0
},
{
title: 'Stan By Me',
year: 1986,
score: 8.6,
rating: 'R',
_id: new ObjectId("6360ec50077f2f2ccc65b30a"),
__v: 0
},
{
title: 'Moonrise Kingdom',
year: 2012,
score: 7.6,
rating: 'PG-13',
_id: new ObjectId("6360ec50077f2f2ccc65b30b"),
__v: 0
}
]
^C
yeji@Yejiui-MacBookAir codeit % node
Welcome to Node.js v16.15.1.
Type ".help" for more information.
> .load index.js
> CONNECTION OPEN!!!
IT WORKED!
[
{
title: 'Amelie',
year: 2001,
score: 8.3,
rating: 'R',
_id: new ObjectId("6360ed32ae081ab37c697437"),
__v: 0
},
{
title: 'Alien',
year: 1979,
score: 8.1,
rating: 'R',
_id: new ObjectId("6360ed32ae081ab37c697438"),
__v: 0
},
{
title: 'The Iron Giant',
year: 1999,
score: 7.5,
rating: 'PG',
_id: new ObjectId("6360ed32ae081ab37c697439"),
__v: 0
},
{
title: 'Stan By Me',
year: 1986,
score: 8.6,
rating: 'R',
_id: new ObjectId("6360ed32ae081ab37c69743a"),
__v: 0
},
{
title: 'Moonrise Kingdom',
year: 2012,
score: 7.6,
rating: 'PG-13',
_id: new ObjectId("6360ed32ae081ab37c69743b"),
__v: 0
}
]
> Movie.find({})
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
_executionStack: null,
mongooseCollection: Collection {
collection: Collection { s: [Object] },
Promise: [Function: Promise],
modelName: 'Movie',
_closed: false,
opts: {
autoIndex: true,
autoCreate: true,
schemaUserProvidedOptions: {},
capped: false,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'movies',
collectionName: 'movies',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: {},
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype],
_readyState: 1,
_closeCalled: undefined,
_hasOpened: true,
plugins: [],
id: 0,
_queue: [],
_listening: false,
_connectionString: 'mongodb://localhost:27017/movieApp',
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise],
db: [Db],
host: 'localhost',
port: 27017,
name: 'movieApp'
},
queue: [],
buffer: false,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { Movie },
schema: Schema {
obj: {
title: [Function: String],
year: [Function: Number],
score: [Function: Number],
rating: [Function: String]
},
paths: {
title: [SchemaString],
year: [SchemaNumber],
score: [SchemaNumber],
rating: [SchemaString],
_id: [ObjectId],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: {
title: [Function: String],
year: [Function: Number],
score: [Function: Number],
rating: [Function: String],
_id: [Object],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object] ],
'$id': 1,
mapPaths: [],
s: { hooks: [Kareem] },
_userProvidedOptions: {},
options: {
typeKey: 'type',
id: true,
_id: true,
validateBeforeSave: true,
read: null,
shardKey: null,
discriminatorKey: '__t',
autoIndex: null,
minimize: true,
optimisticConcurrency: false,
versionKey: '__v',
capped: false,
bufferCommands: true,
strictQuery: true,
strict: true,
pluralization: true
},
'$globalPluginsApplied': true,
_requiredpaths: []
},
op: 'find',
options: {},
_conditions: {},
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: Collection {
collection: [Collection],
Promise: [Function: Promise],
modelName: 'Movie',
_closed: false,
opts: [Object],
name: 'movies',
collectionName: 'movies',
conn: [NativeConnection],
queue: [],
buffer: false,
emitter: [EventEmitter]
},
collectionName: 'movies'
},
_traceFunction: undefined,
'$useProjection': true
}
> Movie.find({}).then(data=> console.log(data))
Promise {
<pending>,
[Symbol(async_id_symbol)]: 603,
[Symbol(trigger_async_id_symbol)]: 601,
[Symbol(destroyed)]: { destroyed: false }
}
> [
{
_id: new ObjectId("6360bee2e3a860c8d3eb165e"),
title: 'Amadeus',
year: 1986,
score: 9.5,
rating: 'R',
__v: 0
},
{
_id: new ObjectId("6360ec50077f2f2ccc65b307"),
title: 'Amelie',
year: 2001,
score: 8.3,
rating: 'R',
__v: 0
},
{
_id: new ObjectId("6360ec50077f2f2ccc65b308"),
title: 'Alien',
year: 1979,
score: 8.1,
rating: 'R',
__v: 0
},
{
_id: new ObjectId("6360ec50077f2f2ccc65b309"),
title: 'The Iron Giant',
year: 1999,
score: 7.5,
rating: 'PG',
__v: 0
},
{
_id: new ObjectId("6360ec50077f2f2ccc65b30a"),
title: 'Stan By Me',
year: 1986,
score: 8.6,
rating: 'R',
__v: 0
},
{
_id: new ObjectId("6360ec50077f2f2ccc65b30b"),
title: 'Moonrise Kingdom',
year: 2012,
score: 7.6,
rating: 'PG-13',
__v: 0
},
{
_id: new ObjectId("6360ed32ae081ab37c697437"),
title: 'Amelie',
year: 2001,
score: 8.3,
rating: 'R',
__v: 0
},
{
_id: new ObjectId("6360ed32ae081ab37c697438"),
title: 'Alien',
year: 1979,
score: 8.1,
rating: 'R',
__v: 0
},
{
_id: new ObjectId("6360ed32ae081ab37c697439"),
title: 'The Iron Giant',
year: 1999,
score: 7.5,
rating: 'PG',
__v: 0
},
{
_id: new ObjectId("6360ed32ae081ab37c69743a"),
title: 'Stan By Me',
year: 1986,
score: 8.6,
rating: 'R',
__v: 0
},
{
_id: new ObjectId("6360ed32ae081ab37c69743b"),
title: 'Moonrise Kingdom',
year: 2012,
score: 7.6,
rating: 'PG-13',
__v: 0
}
]
> Movie.find({rating: 'PG-13'}).then(data=> console.log(data))
Promise {
<pending>,
[Symbol(async_id_symbol)]: 935,
[Symbol(trigger_async_id_symbol)]: 933,
[Symbol(destroyed)]: { destroyed: false }
}
> [
{
_id: new ObjectId("6360ec50077f2f2ccc65b30b"),
title: 'Moonrise Kingdom',
year: 2012,
score: 7.6,
rating: 'PG-13',
__v: 0
},
{
_id: new ObjectId("6360ed32ae081ab37c69743b"),
title: 'Moonrise Kingdom',
year: 2012,
score: 7.6,
rating: 'PG-13',
__v: 0
}
]
> Movie.find({year: {$gte: 2010}}).then(data=>console.log(data))
Promise {
<pending>,
[Symbol(async_id_symbol)]: 1500,
[Symbol(trigger_async_id_symbol)]: 1498,
[Symbol(destroyed)]: { destroyed: false }
}
> [
{
_id: new ObjectId("6360ec50077f2f2ccc65b30b"),
title: 'Moonrise Kingdom',
year: 2012,
score: 7.6,
rating: 'PG-13',
__v: 0
},
{
_id: new ObjectId("6360ed32ae081ab37c69743b"),
title: 'Moonrise Kingdom',
year: 2012,
score: 7.6,
rating: 'PG-13',
__v: 0
}
]
> Movie.updateOne({title: 'Amadeus'}, {year: 1984}).then(res => console.log(res))
Promise {
<pending>,
[Symbol(async_id_symbol)]: 3845,
[Symbol(trigger_async_id_symbol)]: 3843,
[Symbol(destroyed)]: { destroyed: false }
}
> {
acknowledged: true,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1
}
> Movie
Model { Movie }
> Movie.updateMany({title: {$in: ['Amadeus', 'Stan By Me']}}, {score:10}).then(res => console.log(res))
Promise {
<pending>,
[Symbol(async_id_symbol)]: 4559,
[Symbol(trigger_async_id_symbol)]: 4557,
[Symbol(destroyed)]: { destroyed: false }
}
> {
acknowledged: true,
modifiedCount: 3,
upsertedId: null,
upsertedCount: 0,
matchedCount: 3
}
> Movie.findOneAndUpdate({title: 'The Iron Giant'}, {score: 7}).then(m => console.log(m))
Promise {
<pending>,
[Symbol(async_id_symbol)]: 5116,
[Symbol(trigger_async_id_symbol)]: 5114,
[Symbol(destroyed)]: { destroyed: false }
}
> {
_id: new ObjectId("6360ec50077f2f2ccc65b309"),
title: 'The Iron Giant',
year: 1999,
score: 7.5,
rating: 'PG',
__v: 0
}
> Movie.findOneAndUpdate({title: 'The Iron Giant'}, {score: 7}, {new: true}).then(m => console.log(m))
Promise {
<pending>,
[Symbol(async_id_symbol)]: 5325,
[Symbol(trigger_async_id_symbol)]: 5323,
[Symbol(destroyed)]: { destroyed: false }
}
> {
_id: new ObjectId("6360ec50077f2f2ccc65b309"),
title: 'The Iron Giant',
year: 1999,
score: 7,
rating: 'PG',
__v: 0
}
> Movie.remove({title: 'Amelie'}).then(msg => {console.log(msg)})
Promise {
<pending>,
[Symbol(async_id_symbol)]: 5790,
[Symbol(trigger_async_id_symbol)]: 5788,
[Symbol(destroyed)]: { destroyed: false }
}
> (node:2507) [MONGODB DRIVER] Warning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.
(Use `node --trace-warnings ...` to show where the warning was created)
{ acknowledged: true, deletedCount: 2 }
> Movie.deleteMany({year: {$gte: 1999}}).then(msg => console.log(msg))
Promise {
<pending>,
[Symbol(async_id_symbol)]: 6152,
[Symbol(trigger_async_id_symbol)]: 6150,
[Symbol(destroyed)]: { destroyed: false }
}
> { acknowledged: true, deletedCount: 4 }
> Movie.findOneAndDelete({title: 'Alien'}).then(m => console.log(m))
Promise {
<pending>,
[Symbol(async_id_symbol)]: 6547,
[Symbol(trigger_async_id_symbol)]: 6545,
[Symbol(destroyed)]: { destroyed: false }
}
> {
_id: new ObjectId("6360ec50077f2f2ccc65b308"),
title: 'Alien',
year: 1979,
score: 8.1,
rating: 'R',
__v: 0
}
index.js
const mongoose = require('mongoose');
mongoose
.connect('mongodb://localhost:27017/shopApp', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('CONNECTION OPEN!!!');
})
.catch((err) => {
console.log('OH NO ERROR!!!');
console.log(err);
});
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
maxlength: 20,
},
price: {
type: Number,
required: true,
min: [
0,
'Price must be positive ya dodo!', // 에러발생 시 콘솔에서 출력되는 메세지
],
},
onSale: {
type: Boolean,
default: false,
},
categories: [String],
qty: {
online: {
type: Number,
default: 0,
},
inStore: {
type: Number,
default: 0,
},
},
size: {
type: String,
enum: ['S', 'M', 'L'],
},
});
// productSchema.methods.greet = function () {
// console.log('Hello!!!!! HI!!!!!!!!');
// console.log(`- from ${this.name}`);
// };
productSchema.methods.toggleOnsale = function () {
this.onSale = !this.onSale;
return this.save();
};
productSchema.methods.addCategory = function (newCat) {
this.categories.push(newCat);
return this.save();
};
productSchema.statics.fireSale = function () {
return this.updateMany({}, { onSale: true, price: 0 });
};
const Product = mongoose.model('Product', productSchema);
const findProduct = async () => {
const foundProduct = await Product.findOne({ name: 'Mountain Bike' });
console.log(foundProduct);
await foundProduct.toggleOnsale();
console.log(foundProduct);
await foundProduct.addCategory('Outdoors');
console.log(foundProduct);
// foundProduct.onSale = !foundProduct.onSale;
// foundProduct.save();
};
Product.fireSale().then((res) => console.log(res));
// findProduct();
// --- Create ---
// const bike = new Product({
// name: 'Cycling JerSey',
// price: 25.8,
// categories: ['Cycling'],
// size: 'XS',
// });
// bike
// .save()
// .then((data) => {
// console.log('IT WORKED!');
// console.log(data);
// })
// .catch((err) => {
// console.log('OH NO ERROR!');
// // console.log(err.errors.name.properties.message);
// console.log(err);
// });
// --- Update ---
// Product.findOneAndUpdate(
// { name: 'Tire Pump' },
// { price: -100 },
// { new: true, runValidators: true } // runValidators: true 적지 않으면 유효성 검사 없이 변경됨
// )
// .then((data) => {
// console.log('IT WORKED!');
// console.log(data);
// })
// .catch((err) => {
// console.log('OH NO ERROR!');
// console.log(err);
// });
terminal:
...
internal/console/constructor:324:14)
at console.log (node:internal/console/constructor:360:61)
at /Users/yeji/Development/codeit/index.js:49:13
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
errors: {
'categories.2': CastError: Cast to [string] failed for value "[ 'Cycling', 'Safety', [] ]" (type string) at path "categories.2" because of "CastError"
at SchemaArray.cast (/Users/yeji/Development/codeit/node_modules/mongoose/lib/schema/array.js:389:15)
at SchemaArray.SchemaType.applySetters (/Users/yeji/Development/codeit/node_modules/mongoose/lib/schematype.js:1201:12)
at model.$set (/Users/yeji/Development/codeit/node_modules/mongoose/lib/document.js:1410:22)
at model.$set (/Users/yeji/Development/codeit/node_modules/mongoose/lib/document.js:1135:16)
at model.Document (/Users/yeji/Development/codeit/node_modules/mongoose/lib/document.js:166:12)
at model.Model (/Users/yeji/Development/codeit/node_modules/mongoose/lib/model.js:121:12)
at new model (/Users/yeji/Development/codeit/node_modules/mongoose/lib/model.js:5032:15)
at Object.<anonymous> (/Users/yeji/Development/codeit/index.js:35:14)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10) {
stringValue: `"[ 'Cycling', 'Safety', [] ]"`,
messageFormat: undefined,
kind: '[string]',
value: "[ 'Cycling', 'Safety', [] ]",
path: 'categories.2',
reason: [CastError],
valueType: 'string'
}
},
_message: 'Product validation failed'
}
CONNECTION OPEN!!!
^C
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
IT WORKED!
{
name: 'Bike Helmet',
price: 19.5,
onSale: false,
categories: [ 'Cycling', 'Safety' ],
qty: { online: 0, inStore: 0 },
_id: new ObjectId("636106607a6be7a9eb7a4e57"),
__v: 0
}
^C
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
IT WORKED!
{
name: 'Tire Pump',
price: 15.8,
onSale: false,
categories: [ 'Cycling' ],
qty: { online: 0, inStore: 0 },
_id: new ObjectId("636106d0972b2026fb05aba6"),
__v: 0
}
^C
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
IT WORKED!
{
qty: { online: 0, inStore: 0 },
_id: new ObjectId("636106d0972b2026fb05aba6"),
name: 'Tire Pump',
price: 100,
onSale: false,
categories: [ 'Cycling' ],
__v: 0
}
^C
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
IT WORKED!
{
qty: { online: 0, inStore: 0 },
_id: new ObjectId("636106d0972b2026fb05aba6"),
name: 'Tire Pump',
price: -100,
onSale: false,
categories: [ 'Cycling' ],
__v: 0
}
^C
yeji@Yejiui-MacBookAir codeit % node index
OH NO ERROR!
Error: Validation failed: price: Path `price` (-100) is less than minimum allowed value (0).
at ValidationError.inspect (/Users/yeji/Development/codeit/node_modules/mongoose/lib/error/validation.js:50:26)
at formatValue (node:internal/util/inspect:782:19)
at inspect (node:internal/util/inspect:347:10)
at formatWithOptionsInternal (node:internal/util/inspect:2167:40)
at formatWithOptions (node:internal/util/inspect:2029:10)
at console.value (node:internal/console/constructor:324:14)
at console.log (node:internal/console/constructor:360:61)
at /Users/yeji/Development/codeit/index.js:73:13
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
errors: {
price: ValidatorError: Path `price` (-100) is less than minimum allowed value (0).
at validate (/Users/yeji/Development/codeit/node_modules/mongoose/lib/schematype.js:1346:13)
at SchemaNumber.SchemaType.doValidate (/Users/yeji/Development/codeit/node_modules/mongoose/lib/schematype.js:1330:7)
at /Users/yeji/Development/codeit/node_modules/mongoose/lib/helpers/updateValidators.js:151:22
at module.exports (/Users/yeji/Development/codeit/node_modules/mongoose/lib/helpers/updateValidators.js:202:7)
at /Users/yeji/Development/codeit/node_modules/mongoose/lib/query.js:4314:9
at promiseOrCallback (/Users/yeji/Development/codeit/node_modules/mongoose/lib/helpers/promiseOrCallback.js:11:14)
at model.Query.validate (/Users/yeji/Development/codeit/node_modules/mongoose/lib/query.js:4309:10)
at /Users/yeji/Development/codeit/node_modules/kareem/index.js:426:25
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'min',
path: 'price',
value: -100,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'Validation failed'
}
CONNECTION OPEN!!!
^C
yeji@Yejiui-MacBookAir codeit %
yeji@Yejiui-MacBookAir codeit % node index
OH NO ERROR!
Error: Validation failed: price: Price must be positive ya dodo!
at ValidationError.inspect (/Users/yeji/Development/codeit/node_modules/mongoose/lib/error/validation.js:50:26)
at formatValue (node:internal/util/inspect:782:19)
at inspect (node:internal/util/inspect:347:10)
at formatWithOptionsInternal (node:internal/util/inspect:2167:40)
at formatWithOptions (node:internal/util/inspect:2029:10)
at console.value (node:internal/console/constructor:324:14)
at console.log (node:internal/console/constructor:360:61)
at /Users/yeji/Development/codeit/index.js:73:13
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
errors: {
price: ValidatorError: Price must be positive ya dodo!
at validate (/Users/yeji/Development/codeit/node_modules/mongoose/lib/schematype.js:1346:13)
at SchemaNumber.SchemaType.doValidate (/Users/yeji/Development/codeit/node_modules/mongoose/lib/schematype.js:1330:7)
at /Users/yeji/Development/codeit/node_modules/mongoose/lib/helpers/updateValidators.js:151:22
at module.exports (/Users/yeji/Development/codeit/node_modules/mongoose/lib/helpers/updateValidators.js:202:7)
at /Users/yeji/Development/codeit/node_modules/mongoose/lib/query.js:4314:9
at promiseOrCallback (/Users/yeji/Development/codeit/node_modules/mongoose/lib/helpers/promiseOrCallback.js:11:14)
at model.Query.validate (/Users/yeji/Development/codeit/node_modules/mongoose/lib/query.js:4309:10)
at /Users/yeji/Development/codeit/node_modules/kareem/index.js:426:25
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'min',
path: 'price',
value: -100,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'Validation failed'
}
CONNECTION OPEN!!!
^C
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
IT WORKED!
{
name: 'Cycling JerSey',
price: 25.8,
onSale: false,
categories: [ 'Cycling' ],
qty: { online: 0, inStore: 0 },
_id: new ObjectId("636110d1a741f29a5457bd4b"),
__v: 0
}
^C
yeji@Yejiui-MacBookAir codeit % node index
OH NO ERROR!
Error: Product validation failed: size: `XS` is not a valid enum value for path `size`.
at ValidationError.inspect (/Users/yeji/Development/codeit/node_modules/mongoose/lib/error/validation.js:50:26)
at formatValue (node:internal/util/inspect:782:19)
at inspect (node:internal/util/inspect:347:10)
at formatWithOptionsInternal (node:internal/util/inspect:2167:40)
at formatWithOptions (node:internal/util/inspect:2029:10)
at console.value (node:internal/console/constructor:324:14)
at console.log (node:internal/console/constructor:360:61)
at /Users/yeji/Development/codeit/index.js:67:13
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
errors: {
size: ValidatorError: `XS` is not a valid enum value for path `size`.
at validate (/Users/yeji/Development/codeit/node_modules/mongoose/lib/schematype.js:1346:13)
at SchemaString.SchemaType.doValidate (/Users/yeji/Development/codeit/node_modules/mongoose/lib/schematype.js:1330:7)
at /Users/yeji/Development/codeit/node_modules/mongoose/lib/document.js:2877:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'enum',
path: 'size',
value: 'XS',
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'Product validation failed'
}
CONNECTION OPEN!!!
^C
> node
> .load index.js
> const p = new Product({name: 'bike bag', price: 10})
undefined
> p
{
name: 'bike bag',
price: 10,
onSale: false,
categories: [],
qty: { online: 0, inStore: 0 },
_id: new ObjectId("636112295b107c3b203db7a6")
}
> p.greet
[Function (anonymous)]
> p.greet()
Hello!!!!! HI!!!!!!!!
undefined
>
(To exit, press Ctrl+C again or Ctrl+D or type .exit)
>
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
Hello!!!!! HI!!!!!!!!
^C
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
Hello!!!!! HI!!!!!!!!
- from Bike Helmet
^C
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
Hello!!!!! HI!!!!!!!!
- from Mountain Bike
^C
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
{
qty: { online: 0, inStore: 0 },
onSale: false,
categories: [],
_id: new ObjectId("636101d66ce68ea77c61b25e"),
name: 'Mountain Bike',
price: 999,
__v: 0
}
{
qty: { online: 0, inStore: 0 },
onSale: true,
categories: [],
_id: new ObjectId("636101d66ce68ea77c61b25e"),
name: 'Mountain Bike',
price: 999,
__v: 1
}
^C
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
{
qty: { inStore: 0, online: 0 },
_id: new ObjectId("636101d66ce68ea77c61b25e"),
name: 'Mountain Bike',
price: 999,
__v: 1,
categories: [],
onSale: true
}
{
qty: { inStore: 0, online: 0 },
_id: new ObjectId("636101d66ce68ea77c61b25e"),
name: 'Mountain Bike',
price: 999,
__v: 1,
categories: [],
onSale: false
}
{
qty: { inStore: 0, online: 0 },
_id: new ObjectId("636101d66ce68ea77c61b25e"),
name: 'Mountain Bike',
price: 999,
__v: 2,
categories: [ 'Outdoors' ],
onSale: false
}
^C
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
{
qty: { inStore: 0, online: 0 },
_id: new ObjectId("636101d66ce68ea77c61b25e"),
name: 'Mountain Bike',
price: 999,
__v: 2,
categories: [ 'Outdoors' ],
onSale: false
}
{
qty: { inStore: 0, online: 0 },
_id: new ObjectId("636101d66ce68ea77c61b25e"),
name: 'Mountain Bike',
price: 999,
__v: 2,
categories: [ 'Outdoors' ],
onSale: true
}
{
qty: { inStore: 0, online: 0 },
_id: new ObjectId("636101d66ce68ea77c61b25e"),
name: 'Mountain Bike',
price: 999,
__v: 3,
categories: [ 'Outdoors', 'Outdoors' ],
onSale: true
}
^C
yeji@Yejiui-MacBookAir codeit % node index
CONNECTION OPEN!!!
{
acknowledged: true,
modifiedCount: 9,
upsertedId: null,
upsertedCount: 0,
matchedCount: 9
}
터미널이 잘리는구나,,,
person.js
const mongoose = require('mongoose');
mongoose
.connect('mongodb://localhost:27017/shopApp', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('CONNECTION OPEN!!!');
})
.catch((err) => {
console.log('OH NO ERROR!!!');
console.log(err);
});
const personSchema = new mongoose.Schema({
first: String,
last: String,
});
personSchema.virtual('fullName').get(function () {
return `${this.first} ${this.last}`;
});
personSchema.pre('save', async function () {
this.first = 'YO';
this.last = 'MAMA';
console.log('ABOUT TO SAVE!!!');
});
personSchema.post('save', async function () {
console.log('JUST SAVED!!!');
});
const Person = mongoose.model('Person', personSchema);
terminal:
> const tammy = new Person({first: 'Tammy', last:'Chow'})
undefined
> tammy
{
first: 'Tammy',
last: 'Chow',
_id: new ObjectId("6361223a3f91798e85ec31da")
}
> tammy.save(
...
... )
Promise {
<pending>,
[Symbol(async_id_symbol)]: 703,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
}
> tammy.fullName
'Tammy Chow'
> tammy.fullName
'Tammy Chow'
> tammy.fullName = 'Tammy Xiao'
'Tammy Xiao'
> tammy.save()
Promise {
<pending>,
[Symbol(async_id_symbol)]: 1121,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
}
> tammy.fullName
'Tammy Chow'
>