About Mongo

By ukmodak | March 31st 2024 10:32:28 AM | viewed 990 times

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.

General terms about Mongodb ODM

  1. Database—Can contain one or more collections.
  2. Collection—Can contain one or more documents.
  3. Document—Key/Value pair list or array of nested documents.
  4. Schema—Specific data structure of a document.
  5. Model—Constructor that takes a specific schema and create an instance of a document. Models are responsible for creating and reading documents. Schema and Model are somewhat similar, but there is an underlying difference: Schema defines the structure of the document and Model is responsible for creating and reading documents from MongoDB Database.

Data types allowed in schemas

There are eight types of data that can—by default—be set in a Mongoose schema. These are also referred to as SchemaTypes; they are:

  1. String
  2. Number
  3. Date
  4. Boolean
  5. Buffer
  6. ObjectId
  7. Mixed
  8. Array
  9. Decimal128
  10. Map
  11. Schema
String

This SchemaType stores a string value, UTF-8 encoded

Number

This SchemaType stores a number value, with restrictions. Mongoose does not natively support long and double datatypes for example, although MongoDB does. However, Mongoose can be extended using plugins to support these other types. See Chapter 11, Plugins – Re-using Code for more on plugins.

Date

This SchemaType holds a date and time object, typically returned from MongoDB as an ISODate object, for example, ISODate("2013-04-03T12:56:26.009Z")

Boolean

This SchemaType has only two values: true or false.

Buffer

This SchemaType is primarily used for storing binary information, for example, images stored in MongoDB.ObjectId

const schema1 = new Schema({ binData: Buffer }); // binData will be cast to a Buffer
const schema2 = new Schema({ binData: 'Buffer' }); // Equivalent
const Data = mongoose.model('Data', schema2);
Mixed

An "anything goes" SchemaType. Mongoose will not do any casting on mixed paths. You can define a mixed path using Schema.Types.Mixed or by passing an empty object literal. The following are equivalent.

const Any = new Schema({ any: {} });
const Any = new Schema({ any: Object });
const Any = new Schema({ any: Schema.Types.Mixed });
const Any = new Schema({ any: mongoose.Mixed });
ObjectIds

An ObjectId is a special type typically used for unique identifiers. Here's how you declare a schema with a path driver that is an ObjectId:

Arrays

Mongoose supports arrays of SchemaTypes and arrays of subdocuments. Arrays of SchemaTypes are also called primitive arrays, and arrays of subdocuments are also called document arrays.

const ToySchema = new Schema({ name: String });
const ToyBoxSchema = new Schema({
  toys: [ToySchema],
  buffers: [Buffer],
  strings: [String],
  numbers: [Number]
});
Maps

A MongooseMap is a subclass of JavaScript's Map class. In these docs, we'll use the terms 'map' and MongooseMap interchangeably. In Mongoose, maps are how you create a nested document with arbitrary keys.Note: In Mongoose Maps, keys must be strings in order to store the document in MongoDB.

const userSchema = new Schema({
  // `socialMediaHandles` is a map whose values are strings. A map's
  // keys are always strings. You specify the type of values using `of`.
  socialMediaHandles: {
    type: Map,
    of: String
  }
});

const User = mongoose.model('User', userSchema);
// Map { 'github' => 'vkarpov15', 'twitter' => '@code_barbarian' }
console.log(new User({
  socialMediaHandles: {
    github: 'vkarpov15',
    twitter: '@code_barbarian'
  }
}).socialMediaHandles);

The above example doesn't explicitly declare github or twitter as paths, but, since socialMediaHandles is a map, you can store arbitrary key/value pairs. However, since socialMediaHandles is a map, you must use .get() to get the value of a key and .set() to set the value of a key.

const user = new User({
  socialMediaHandles: {}
});

// Good
user.socialMediaHandles.set('github', 'vkarpov15');
// Works too
user.set('socialMediaHandles.twitter', '@code_barbarian');
// Bad, the `myspace` property will **not** get saved
user.socialMediaHandles.myspace = 'fail';

// 'vkarpov15'
console.log(user.socialMediaHandles.get('github'));
// '@code_barbarian'
console.log(user.get('socialMediaHandles.twitter'));
// undefined
user.socialMediaHandles.github;

// Will only save the 'github' and 'twitter' properties
user.save();
Schemas

To declare a path as another schema, set type to the sub-schema's instance. To set a default value based on the sub-schema's shape, simply set a default value, and the value will be cast based on the sub-schema's definition before being set during document creation.

const subSchema = new mongoose.Schema({
  // some schema definition here
});

const schema = new mongoose.Schema({
  data: {
    type: subSchema
    default: {}
  }
});

Schema type validation


Tutorial Link
Tutorial Link
Tutorial Link
bONEandALL
Visitor

Total : 26654

Today :3

Today Visit Country :

  • France
  • United States