📜  npm mongoose - Javascript (1)

📅  最后修改于: 2023-12-03 15:33:13.062000             🧑  作者: Mango

Introduction to npm mongoose - Javascript

Mongoose is a popular Object-Document Mapping (ODM) library for Node.js and MongoDB. It allows developers to define the data schema and interact with MongoDB databases using Node.js.

Features
  • Schema-based modeling
  • Data validation
  • Simple query building
  • Middleware support
  • Index and unique key support
  • Populate() method for data population across collections
Installing Mongoose

Mongoose can be installed using npm:

npm install mongoose
Connecting to MongoDB

Before using Mongoose to interact with MongoDB, the connection to the database needs to be established. This can be done using the connect() method:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true });
Defining a Schema

A schema defines the structure of the document and the types of each field. Here's an example of a schema definition using Mongoose:

const kittySchema = new mongoose.Schema({
  name: String,
  age: Number
});
Creating a Model

A model is a class that represents a collection in the database. To create a model, we can use the mongoose.model() method:

const Kitten = mongoose.model('Kitten', kittySchema);
Saving a Document

To save a document to the database, we need to create an instance of the model and call the save() method:

const fluffy = new Kitten({ name: 'Fluffy', age: 3 });

fluffy.save(function (err, fluffy) {
  if (err) return console.error(err);
  console.log('Saved successfully!');
});
Querying for Documents

Mongoose provides several methods for querying the database, such as find(), findOne(), and findById(). Here's an example of using the find() method:

Kitten.find({ age: { $gt: 2 } }, function (err, kittens) {
  if (err) return console.error(err);
  console.log(kittens);
});
Conclusion

Mongoose is a powerful ODM library that simplifies the interaction between Node.js and MongoDB. By defining a schema and creating a model, developers can easily perform CRUD operations and manipulate data in a structured and organized way.