📅  最后修改于: 2023-12-03 15:33:13.062000             🧑  作者: Mango
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.
Mongoose can be installed using npm:
npm install mongoose
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 });
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
});
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);
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!');
});
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);
});
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.