How to use the Schema function from mongoose

Find comprehensive JavaScript mongoose.Schema code examples handpicked from public code repositorys.

mongoose.Schema is a constructor function in the Mongoose library that defines the structure of documents for a MongoDB collection.

3
4
5
6
7
8
9
10
11
12
const { isEmail } = require('validator');

// <https://github.com/Automattic/mongoose/issues/5534>
mongoose.Error.messages = require('@ladjs/mongoose-error-messages');

const UpgradeReminders = new mongoose.Schema({
  // this is the FQDN that the upgrade is regarding
  domain: {
    type: String,
    required: true,
fork icon71
star icon556
watch icon8

184
185
186
187
188
189
190
191
192
193
``` js
let mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/test') // 记得先连接到数据库

/** 定义表结构 **/
let emailSchema = new mongoose.Schema({
  email: String,
  date: Date
})
// 回调钩子
fork icon52
star icon299
watch icon8

How does mongoose.Schema work?

mongoose.Schema is a constructor function in the Mongoose library that defines the structure of documents for a MongoDB collection. When you call mongoose.Schema(definition, options), it returns a new schema object that defines the structure of documents in a MongoDB collection. The definition parameter is an object that specifies the fields and data types of the documents, while the options parameter is an optional object that allows you to configure the schema. Here are some common options that can be used with mongoose.Schema: collection: specifies the name of the MongoDB collection to use for this schema. timestamps: specifies whether or not to automatically add createdAt and updatedAt timestamps to the documents. strict: specifies whether or not to enforce a strict schema, which will prevent documents from being saved if they contain properties not defined in the schema. validateBeforeSave: specifies whether or not to run validation on the document before saving it to the database. Once you have defined a schema using mongoose.Schema, you can create a model from it by calling mongoose.model(name, schema). This creates a new model object that you can use to interact with the corresponding MongoDB collection. Overall, mongoose.Schema is a powerful tool in the Mongoose library that allows you to define the structure of documents in a MongoDB collection, and can be customized using various options.

-2
fork icon83
star icon272
watch icon33

+ 9 other calls in file

-2
fork icon81
star icon254
watch icon19

+ 15 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const blogPostSchema = new Schema({
  title: String,
  content: String,
  author: {
    type: Schema.Types.ObjectId,
    ref: "User",
  },
  comments: [
    {
      type: Schema.Types.ObjectId,
      ref: "Comment",
    },
  ],
});

const BlogPost = mongoose.model("BlogPost", blogPostSchema);

module.exports = BlogPost;

In this example, we first import the mongoose library and define a new Schema variable using mongoose.Schema. We then define a new blogPostSchema object that specifies the fields and data types of the documents in the MongoDB collection. This schema includes four fields: title: a string that represents the title of the blog post. content: a string that represents the content of the blog post. author: a reference to a User object in the database, using the Schema.Types.ObjectId data type. comments: an array of references to Comment objects in the database, also using the Schema.Types.ObjectId data type. We then create a new BlogPost model using mongoose.model(name, schema), and export it as a module. Overall, this example demonstrates how to use mongoose.Schema to define the structure of documents in a MongoDB collection, including fields and data types.

176
177
178
179
180
181
182
183
184
185

```
var mongoose = require('mongoose');

// 定义Schema
UserSchema = new mongoose.Schema({
  username: {// 真实姓名
    type: String,
    required: true
  },
fork icon35
star icon175
watch icon9

+ 3 other calls in file

57
58
59
60
61
62
63
64
65
66
With Mongoose, everything is derived from a Schema. Lets create a schema.

```js
var mongoose = require('mongoose');
        
var Schema = mongoose.Schema;

var AutoSchema = new Schema({
    name : String,
    countOf: Number,
fork icon220
star icon163
watch icon8

70
71
72
73
74
75
76
77
78
79
   * @api private
   */
adapter._models = {};

adapter.schema = function(name, schema, options) {
  var Mixed = mongoose.Schema.Types.Mixed;

  schema._id = {
    type: String,
    default: function() {
fork icon135
star icon69
watch icon12

+ 11 other calls in file

88
89
90
91
92
93
94
95
96
97
```javascript
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/test');

const schema = new mongoose.Schema({ name: String });
const User = mongoose.model('User', schema);

// Will still work, even though connection hasn't been established when
// `create()` is called
fork icon54
star icon125
watch icon10

+ 3 other calls in file

13
14
15
16
17
18
19
20
21
22

const mongoDB = new mongod({
  port: port,
  dbpath: path.join(__dirname, '..', dbpath)
});
const videoObjectSchema = new mongoose.Schema({
  url: String,          //  /video/number
  aliasUrl: String,     //  /episode/example-title

  aired: String, //"2016-07-17",
fork icon10
star icon49
watch icon5

+ 3 other calls in file

9
10
11
12
13
14
15
16
17
18
    mongo_connection_string = 'mongodb://localhost/redisfire';
}

var connections = [];

var redisfire_auth_schema = new mongoose.Schema({
    key: {
      type: String
    },
    createdAt: {
fork icon11
star icon36
watch icon7

0
1
2
3
4
5
6
7
8
9
10
11
12
13


const mongoose = require("mongoose");


mongoose.connect(mongodb, { useNewUrlParser: true, useUnifiedTopology: true });


const economySchema = new mongoose.Schema({
  userId: String ,


  wallet: { 
    type: Number,
fork icon27
star icon8
watch icon0

1
2
3
4
5
6
7
8
9
10
11
12
13




/**
 * Defines the schema of the payment resource to be stored in the DB
 */
const paymentSchema = new mongoose.Schema({


    bookingId: {
        type: mongoose.SchemaTypes.ObjectId,
        required: true,
fork icon3
star icon2
watch icon0

2
3
4
5
6
7
8
9
10
11
12
const jobApplication = require('./jobApplication');


/**
 * User Schema
 */
const userSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
fork icon0
star icon3
watch icon1

+ 3 other calls in file

0
1
2
3
4
5
6
7
8
9
10
const crypto = require("crypto");
const mongoose = require("mongoose");
const validator = require("validator");
const bcrypt = require("bcrypt");


const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "Please tell us your name!"],
  },
fork icon0
star icon1
watch icon1

-3
fork icon0
star icon1
watch icon0

+ 23 other calls in file

51
52
53
54
55
56
57
58
59
60
  type: String,
  minlength: [1, 'Country is required'],
  required: [true, 'Country is required']
},
cart: {
  type: mongoose.Schema.ObjectId,
  ref: 'carts',
},
date: {
  type: Date,
fork icon0
star icon1
watch icon0