📜  node js + mongoose - Javascript (1)

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

Node.js + Mongoose - Javascript

Node.js is a popular Javascript runtime built on the V8 engine. Mongoose is a popular Object-Document Mapping (ODM) library for MongoDB written in Javascript. Together, they provide a powerful and flexible solution for building server-side applications.

Getting started with Node.js & Mongoose

To get started with Node.js, you need to install it on your machine. You can download the latest version from the official Node.js website (https://nodejs.org/en/).

Once you have installed Node.js, you can create a new Node project by running the following command in your terminal:

npm init

This will generate a package.json file in your project directory. This file contains information about your project and its dependencies.

Next, you need to install Mongoose. You can do this by running the following command:

npm install mongoose

This will download and install the latest version of Mongoose.

Connecting to MongoDB with Mongoose

To connect to a MongoDB database using Mongoose, you need to create a new instance of the mongoose module and call the connect() method, passing in the URL of your MongoDB server.

Here's an example:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('Connected to MongoDB!');
});

In this example, we're connecting to a local MongoDB server running on localhost and using the mydatabase database.

The useNewUrlParser and useUnifiedTopology options are required starting from MongoDB v3.1.0. They enable new features and improve the performance of the MongoDB driver.

Defining Mongoose Schemas and Models

Once you have connected to your MongoDB database, you can start defining Mongoose schemas and models to represent your data.

A schema is a blueprint for a collection of documents in MongoDB. It defines the shape and validation rules of the documents. A model is a constructor for creating instances of documents based on a schema.

Here's an example of a simple Mongoose schema and model for a blog post:

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
  title: { type: String, required: true },
  content: { type: String, required: true },
  author: { type: String, required: true },
  createdAt: { type: Date, default: Date.now }
});

const Post = mongoose.model('Post', postSchema);

module.exports = Post;

In this example, we define a schema for a blog post with four fields: title, content, author, and createdAt. The title, content, and author fields are required, while the createdAt field is optional and has a default value of the current date and time.

We then create a model called Post based on the postSchema and export it as a module.

Using Mongoose Models to Query MongoDB

Once you have defined Mongoose models for your data, you can use them to interact with your MongoDB database.

Here are some examples of common operations:

Creating a new document
const Post = require('./models/post');

const newPost = new Post({
  title: 'My first post',
  content: 'Hello, world!',
  author: 'John Doe'
});

newPost.save(function(err, post) {
  if (err) console.error(err);
  console.log(post);
});

In this example, we create a new instance of the Post model and call the save() method to insert a new document into the posts collection in our MongoDB database. The callback function is called once the insertion is complete, and it either logs the new document or an error if there was one.

Retrieving documents
const Post = require('./models/post');

Post.find({}, function(err, posts) {
  if (err) console.error(err);
  console.log(posts);
});

In this example, we retrieve all documents from the posts collection by calling the find() method on the Post model with an empty query object. The callback function is called with an array of documents or an error if there was one.

Updating documents
const Post = require('./models/post');

Post.findOneAndUpdate({ title: 'My first post' }, { content: 'Hello, the world is a beautiful place!' }, function(err, post) {
  if (err) console.error(err);
  console.log(post);
});

In this example, we update a single document in the posts collection by calling the findOneAndUpdate() method on the Post model. We pass in a query object to find the document we want to update ({ title: 'My first post' }) and an update object to set the new value ({ content: 'Hello, the world is a beautiful place!' }). The callback function is called with the updated document or an error if there was one.

Deleting documents
const Post = require('./models/post');

Post.findOneAndDelete({ title: 'My first post' }, function(err, post) {
  if (err) console.error(err);
  console.log(post);
});

In this example, we delete a single document from the posts collection by calling the findOneAndDelete() method on the Post model. We pass in a query object to find the document we want to delete ({ title: 'My first post' }). The callback function is called with the deleted document or an error if there was one.

Conclusion

Node.js and Mongoose provide a powerful and flexible solution for building server-side applications with Javascript. In this guide, we covered the basics of connecting to a MongoDB database with Mongoose, defining schemas and models, and using Mongoose models to perform common CRUD operations on the database.

To learn more about Node.js and Mongoose, check out the official documentation:

  • Node.js: https://nodejs.org/en/docs/
  • Mongoose: https://mongoosejs.com/docs/