Mongoose는 Node.js와 MongoDB를 위한 ODM(Object Data Mapping) library이다.
command 창에 아래의 명령을 입력한다.
$ npm install mongoose --save
- Defining your schema
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.- Creating a model
To use our schema definition, we need to convert our Schema into a Model we can work with. To do so, we pass it intomongoose.model(modelName, schema) //modelName: mongoDB에 저장될 파일 이름
import mongoose from 'mongoose';
const { Schema } = mongoose;
// 1. Defining your schema
const blogSchema = new Schema({
title: String, // String is shorthand for {type: String}
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});
// 2. Creating a model
const Blog = mongoose.model('Blog', blogSchema);
Model.exists()
Returns a document with _id only if at least one document exists in the database that matches the given filter, and null otherwise.
const blog = await Blog.exists(id)
// exists(id) is a shorthand for exists({ _id: id })
Statics
You can also add static functions to your model. One way to add static isSchema.static()
// blogSchema를 정의한 후에 static함수를 사용한다.
blogSchema.static("formatHashtags", function (hashtags) {
return hashtags
.split(",")
.map((word) => (word.startsWith("#") ? word : `#${word}`));
});
const Blog = mongoose.model('Blog', blogSchema)
// model을 만들고, 위의 static함수를 이용해 만든 formatHashtags사용 예시.
const hashtags = Blog.formatHashtags(hashtags)
Model.find()
Finds documents.
// find all documents
await Blog.find({});
자료 출처