First Mongoose Model

  • 为什么要使用mongoose?

使用一种更简单的方式来使mongoDB和JS之间进行连接

  • 如何使用mongoose?
  1. npm i init -y
  2. npm i mongoose

  3. 在index.js里面require mongoose.
  4. 连接->测试连接是否成功
index.js

const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/MovieDB', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log("Connected") }) .catch(err => { console.log("error!") console.log(err) }) // 如何缩进?选中代码块,右键,foramt selection. // 帮助文档的测试连接方法,我们也可以直接用上面的then, catch 方法 const db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function () { console.log("Yayyyy, connected!") });
//Schema,相当于创建一个指定数据类型的数据表
const movieSchema = new mongoose.Schema({
    title: String,
    year: Number,
    score: Number,
    rating: String
});

//model.用我们所设定的shema来实力化的东西
// An instance of a model is called a document.
//Models are responsible for creating and reading documents from the underlying MongoDB database.
const Movie = mongoose.model('Movie', movieSchema);   //Mongo will create a collection called movies by our input "Movie"
//相当于插入了一条实例数据到Movie里main
const amadeus = new Movie({ title: 'Amadeus', year: 1986, score: 9.2, rating: 'R' });

  step 1: 让index.js连接到mongo: node->.load index.js

此时回到mongo的话(.exit回到 mongp shell),amadeus并没有被保存(下面的代码应该是use MovieDB)

   movies 就是那个model根据我们给的"Movie"给我们自动生成的一个document.

  • 怎么保存呢?

回到 step 1: 让index.js连接到mongo: node->.load index.js,amadeus.save()

保存之后我们再去mongo shell看

为什么是use MovieDB? 因为我们在一开始连接mongoose的时候取的名字就是MovieDB.

原文地址:https://www.cnblogs.com/LilyLiya/p/14392512.html