MongoDB Node

施琦
2023-12-01

文档

前置工作:

  1. 安装本地mongoDB,并且启动「本地可以随便造」
  2. 安装可视化工具MongoDB Compass

开始啦

新建一个本地空项目

npm init
npm install mongoose --save

新建一个文件

// app.js
// 第一步、链接mongo
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', mongoOpen);
// 第二部、成功回调里面进行操作
async function mongoOpen() {
  // we're connected!
  console.log('mongo open success');
  // 定义一个Schema,对应到mongo数据库的collection,类似于定义一个表
  // 当前Schema只有一个属性--name
  var kittySchema = mongoose.Schema({
    name: String
  });
  kittySchema.methods.speak = function () {
    var greeting = this.name
      ? "Meow name is " + this.name
      : "I don't have a name";
    console.log(greeting);
  }
  var Kitten = mongoose.model('Kitten', kittySchema);
  // 新建数据
  var felyne = new Kitten({ name: 'Felyne' });
  // 就算添加其他属性,能够成功执行,但是不会保存上
  var fluffy = new Kitten({ name: 'fluffy' });
  var empty = new Kitten();

  // 添加
  await fluffy.save().then((v) => v.speak()); // 是个异步函数
  await empty.save();
  empty.speak();
  const saveRes = await felyne.save();
  felyne.speak();
  console.log('saveRes', saveRes);
  // => saveRes { _id: 5f02e434c4946e1642054c17, name: 'Felyne', __v: 0 }

  // 查询
  const list = await Kitten.find({ name: /^[fF]/})
  console.log('find res', list);
  console.log('find all res', await Kitten.find({}));

  // 修改
  const updateRes = await Kitten.updateMany(
    { name: undefined },
    { name: 'fff' }
  );
  console.log('updateRes', updateRes);
  // => updateRes { n: 1, nModified: 1, ok: 1 }
  console.log('update find res', await Kitten.find({}));

  // 删除
  const deleteRes = await Kitten.deleteMany({ name: /^[fF]/});
  console.log('deleteRes', deleteRes);
  // => deleteRes { n: 3, ok: 1, deletedCount: 3 }
  console.log('delete find res', await Kitten.find({}));
}

运行

node app.js

输出

mongo open success
Meow name is fluffy
I don't have a name
Meow name is Felyne
find res [
  { _id: 5f02e30820b51d14acdfec20, name: 'fluffy', __v: 0 },
  { _id: 5f02e30820b51d14acdfec1f, name: 'Felyne', __v: 0 }
]
find all res [
  { _id: 5f02e30820b51d14acdfec20, name: 'fluffy', __v: 0 },
  { _id: 5f02e30820b51d14acdfec21, __v: 0 },
  { _id: 5f02e30820b51d14acdfec1f, name: 'Felyne', __v: 0 }
]
updateRes { n: 1, nModified: 1, ok: 1 }
update find res [
  { _id: 5f02e30820b51d14acdfec20, name: 'fluffy', __v: 0 },
  { _id: 5f02e30820b51d14acdfec21, __v: 0, name: 'fff' },
  { _id: 5f02e30820b51d14acdfec1f, name: 'Felyne', __v: 0 }
]
deleteRes { n: 3, ok: 1, deletedCount: 3 }
delete find res []
 类似资料:

相关阅读

相关文章

相关问答