欢迎访问宙启技术站
智能推送

express使用Mongoose连接MongoDB操作示例【附源码下载】

发布时间:2023-05-16 03:21:13

使用Mongoose连接MongoDB需要先安装Mongoose和MongoDB数据库,本文将演示如何使用Mongoose连接MongoDB进行基本的crud操作。

1.安装Mongoose

在命令行中输入:

npm install mongoose

2.连接MongoDB

在app.js中引用mongoose模块,并连接MongoDB数据库:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mongooseTest');

其中,'mongodb://localhost:27017/mongooseTest'表示连接数据库的URL,mongooseTest为要连接的数据库名称。

3.定义Schema和Model

在app.js中定义Schema和Model:

const personSchema = mongoose.Schema({

  name: String,

  age: Number,

  sex: String,

  hobbies: [String]

});

const Person = mongoose.model('Person', personSchema);

其中,personSchema为定义的Schema,Person为定义的Model。

4.新增数据

在app.js中新增一条数据并保存:

const person = new Person({

  name: 'Tom',

  age: 18,

  sex: 'male',

  hobbies: ['basketball', 'reading']

});

person.save().then(() => {

  console.log('新增成功');

}).catch(err => {

  console.log(err);

});

其中,person为要新增的数据对象,save()方法为保存数据,then()方法为保存成功后的回调函数,catch()方法为保存失败后的回调函数。

5.查询数据

在app.js中查询所有数据:

Person.find().then(result => {

  console.log('查询结果:', result);

}).catch(err => {

  console.log(err);

});

其中,find()方法为查询所有数据,then()方法为查询成功后的回调函数,catch()方法为查询失败后的回调函数。

6.更新数据

在app.js中更新一条数据:

Person.updateOne({ name: 'Tom' }, { age: 20 }).then(() => {

  console.log('更新成功');

}).catch(err => {

  console.log(err);

});

其中,updateOne()方法为更新一条数据, 个参数为要更新的条件,第二个参数为要更新的数据,then()方法为更新成功后的回调函数,catch()方法为更新失败后的回调函数。

7.删除数据

在app.js中删除一条数据:

Person.deleteOne({ name: 'Tom' }).then(() => {

  console.log('删除成功');

}).catch(err => {

  console.log(err);

});

其中,deleteOne()方法为删除一条数据,参数为要删除的条件,then()方法为删除成功后的回调函数,catch()方法为删除失败后的回调函数。

完整的app.js代码如下:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mongooseTest');

const personSchema = mongoose.Schema({

  name: String,

  age: Number,

  sex: String,

  hobbies: [String]

});

const Person = mongoose.model('Person', personSchema);

const person = new Person({

  name: 'Tom',

  age: 18,

  sex: 'male',

  hobbies: ['basketball', 'reading']

});

person.save().then(() => {

  console.log('新增成功');

}).catch(err => {

  console.log(err);

});

Person.find().then(result => {

  console.log('查询结果:', result);

}).catch(err => {

  console.log(err);

});

Person.updateOne({ name: 'Tom' }, { age: 20 }).then(() => {

  console.log('更新成功');

}).catch(err => {

  console.log(err);

});

Person.deleteOne({ name: 'Tom' }).then(() => {

  console.log('删除成功');

}).catch(err => {

  console.log(err);

});

运行以上代码,在命令行中输入:

node app.js

即可进行基本的mongodb操作。

本文示例代码下载地址:https://github.com/Tualatin/mongoose-mongodb.git