Appearance
安装
javascript
npm install mongodb --save连接数据库
javascript
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});插入文档
javascript
const insertDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}查找所有文档
javascript
const findDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs)
callback(docs);
});
}更新文档
javascript
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
updateDocument(db, function() {
client.close();
});
});
});删除文档
javascript
const removeDocument = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Delete document where a is 3
collection.deleteOne({ a : 3 }, function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log("Removed the document with the field a equal to 3");
callback(result);
});
}mongoose使用
链接数据库
javascript
mongoose.connect('mongodb://localhost:27017/itcast', {useNewUrlParser: true, useUnifiedTopology: true});设计表结构
javascript
const Schema = mongoose.Schema
const userSchema = new Schema({
username:{
type:String,
required:true
},
password:{
type:String,
required:true
},
email:{
type:String
}
});将文档结构发布为模型
第一个参数要大写,最终数据库中会将该字符串变为该字符串的小写的复数(users)
javascript
const User = mongoose.model('User', userSchema)对模型进行增删改查
新增数据
javascript
var admin = new User({
username:'admin',
password:'123',
email:'1225348331@qq.com'
})
//对数据进行持久化
admin.save(function(err,result){
if(err){
console.log('存储失败')
}
console.log('保存成功了')
console.log(result)
})查询数据
javascript
//第一个参数为查询条件
User.find({
username:"admin",
password:"123"
},function(err,data){
if(err){
console.log(err)
}
console.log(data)
})