文章目录
前言
一、安装mongoose
代码如下:
npm install mongoose
二、连接数据库
方法原型:
Mongoose.prototype.connect()
Parameters
uri(s) «String»
[options] «Object» passed down to the MongoDB driver's connect() function, except for 4 mongoose-specific options explained below.
[options.user] «String» username for authentication, equivalent to options.auth.user. Maintained for backwards compatibility.
[options.pass] «String» password for authentication, equivalent to options.auth.password. Maintained for backwards compatibility.
[options.autoIndex=true] «Boolean» Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
[options.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to disable buffering on all models associated with this connection.
[callback] «Function»
Returns:
«Promise» resolves to `this` if connection succeeded
代码如下:
const mongoose = require('mongoose')
// 连接数据库
mongoose.connect('mongodb://localhost/test', (err) => {
if (err)
return err
console.log('数据库连接成功')
})
执行结果:
数据库连接成功
连接数据库,需要创建集合后才会显示数据库:
三、创建集合
方法原型:
Schema()
Parameters
definition «Object»
[options] «Object»
Mongoose.prototype.model()
Parameters
name «String|Function» model name or class extending Model
[schema] «Schema» the schema to use.
[collection] «String» name (optional, inferred from model name)
Returns:
«Model» The model associated with name. Mongoose will create the model if it doesn't already exist.
代码如下:
// 创建Schema
const booksSchema = new mongoose.Schema({
name: String,
author: String,
type: String
})
// 第一个参数是跟model对应的集合(collection)名字的单数形式。Mongoose会自动找到名称是model名字复数形式的collection。
// Books是model的实例。
const Books = mongoose.model('book', booksSchema)
books集合创建成功:
四、插入文档
方法原型:
Parameters
docs «Array|Object» Documents to insert, as a spread or array
[options] «Object» Options passed down to save(). To specify options, docs must be an array, not a spread.
[callback] «Function» callback
Returns:
«Promise»
代码如下:
Books.create({ name: '凡人修仙传', author: '忘语', type: '仙侠修真' }, (err, result) => {
if (err)
return err
console.log(result)
})
执行结果:
{
name: '凡人修仙传',
author: '忘语',
type: '仙侠修真',
_id: new ObjectId("61de6d837a2a6f0bed22c5d0"),
__v: 0
}
数据插入成功
五、查询文档
为了更好的演示效果,插入了几个文档
1、查询一条文档
方法原型:
Model.findOne()
Parameters
[conditions] «Object»
[projection] «Object|String|Array<String>» optional fields to return, see Query.prototype.select()
[options] «Object» optional see Query.prototype.setOptions()
[callback] «Function»
Returns:
«Query»
Finds one document.
代码如下:
Books.findOne({ author: '忘语' }, (err, result) => {
if (err)
return err
console.log(result)
})
执行结果:
{
_id: new ObjectId("61de6d837a2a6f0bed22c5d0"),
name: '凡人修仙传',
author: '忘语',
type: '仙侠修真',
__v: 0
}
2、查询所有文档
方法原型:
Model.find()
Parameters
filter «Object|ObjectId»
[projection] «Object|String|Array<String>» optional fields to return, see Query.prototype.select()
[options] «Object» optional see Query.prototype.setOptions()
[callback] «Function»
Returns:
«Query»
Finds documents
代码如下:
Books.find({}, (err, result) => {
if (err)
return err
console.log(result)
})
执行结果:
// 返回文档集合(数组)
[
{
_id: new ObjectId("61de6d837a2a6f0bed22c5d0"),
name: '凡人修仙传',
author: '忘语',
type: '仙侠修真',
__v: 0
},
{
_id: new ObjectId("61de75c5693b87b424b5586d"),
name: '重生之都市修仙',
author: '十里剑神',
type: '重生修真',
__v: 0
},
{
_id: new ObjectId("61de75c5693b87b424b5586e"),
name: '最强装逼打脸系统',
author: '太上布衣',
type: '装逼修真',
__v: 0
},
{
_id: new ObjectId("61de7717872b8a4ca520e8ab"),
name: '大奉打更人',
author: '卖报小郎君',
type: '探案仙侠',
__v: 0
},
{
_id: new ObjectId("61de7717872b8a4ca520e8ac"),
name: '凡人修仙之仙界篇',
author: '忘语',
type: '仙侠修真',
__v: 0
}
]
3、查询所有符合条件的文档
代码如下:
Books.find({ author: '忘语' }, (err, result) => {
if (err)
return err
console.log(result)
})
执行结果:
[
{
_id: new ObjectId("61de6d837a2a6f0bed22c5d0"),
name: '凡人修仙传',
author: '忘语',
type: '仙侠修真',
__v: 0
},
{
_id: new ObjectId("61de7717872b8a4ca520e8ac"),
name: '凡人修仙之仙界篇',
author: '忘语',
type: '仙侠修真',
__v: 0
}
]
六、更新文档
1、更新一条文档
方法原型:
Model.updateOne()
Parameters
filter «Object»
update «Object|Array»
[options] «Object» optional see Query.prototype.setOptions()
[options.strict] «Boolean|String» overwrites the schema's strict mode option
[options.upsert=false] «Boolean» if true, and no documents found, insert a new document
[options.writeConcern=null] «Object» sets the write concern for replica sets. Overrides the schema-level write concern
[options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.
[callback] «Function» params are (error, writeOpResult)
Returns:
«Query»
代码如下:
Books.updateOne({ name: '凡人修仙传' }, { name: '凡人' }, (err, result) => {
if (err)
return err
console.log(result)
})
执行结果:
{
acknowledged: true,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1
}
文档更新成功:
2、更新多条文档
方法原型:
Model.updateMany()
Parameters
filter «Object»
update «Object|Array»
[options] «Object» optional see Query.prototype.setOptions()
[options.strict] «Boolean|String» overwrites the schema's strict mode option
[options.upsert=false] «Boolean» if true, and no documents found, insert a new document
[options.writeConcern=null] «Object» sets the write concern for replica sets. Overrides the schema-level write concern
[options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
[callback] «Function» function(error, res) {} where res has 5 properties: modifiedCount, matchedCount, acknowledged, upsertedId, and upsertedCount.
Returns:
«Query»
代码如下:
Books.updateMany({ type: '仙侠修真' }, { type: '玄幻修真' }, (err, result) => {
if (err)
return err
console.log(result)
})
执行结果:
{
acknowledged: true,
modifiedCount: 2,
upsertedId: null,
upsertedCount: 0,
matchedCount: 2
}
文档更新成功:
七、删除文档
1、删除一条文档
方法原型:
Model.findOneAndDelete()
Parameters
conditions «Object»
[options] «Object» optional see Query.prototype.setOptions()
[options.strict] «Boolean|String» overwrites the schema's strict mode option
[options.projection=null] «Object|String|Array<String>» optional fields to return, see Query.prototype.select()
[options.session=null] «ClientSession» The session associated with this query. See transactions docs.
[callback] «Function»
Returns:
«Query»
代码如下:
Books.findOneAndDelete({ name: '凡人' }, (err, result) => {
if (err)
return err
console.log(result)
})
执行结果:
{
_id: new ObjectId("61de6d837a2a6f0bed22c5d0"),
name: '凡人',
author: '忘语',
type: '玄幻修真',
__v: 0
}
文档删除成功:
2、删除多条文档
方法原型:
Model.deleteMany()
Parameters
conditions «Object»
[options] «Object» optional see Query.prototype.setOptions()
[callback] «Function»
Returns:
«Query»
代码如下:
Books.deleteMany({ name: '大奉打更人' }, (err, result) => {
if (err)
return err
console.log(result)
})
执行结果:
{ deletedCount: 1 }
文档删除成功:
总结
更多API可以查看mongoose文档请点击这里