Mongoose

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { Schema } from 'mongoose';
import mongoose from 'mongoose';

// create schema
const blogSchema = new Schema({ name: String, type: String }, {
// add shcema method
methods: {
// 不要使用`() => {}`,会影响this绑定
findSimilarTypes(cb) {
return mongoose.model('Blog').find({ type: this.type }, cb);
}
}
});
// Add schema method with another way
blogSchema.methods.findSimilarTypes = function(cb) {
return mongoose.model('Blog').find({ type: this.type }, cb);
}
// create model
const Blog = mongoose.model('Blog', blogSchema);
// save model in mongodb
// `_id` 创建model会自动添加_id字段
const bo = new Blog();
await bo.save()

本文作者: 孟 虎
本文链接: https://menghu1994.github.io/blog/2024/09/Nodejs/MongoDB/mongoose/index/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!