Mongoose是在node.js环境下对mongodb进行便捷操作的对象模型工具。
mongoose.connect(url(s), [options], [callback])
//url(s):数据库地址,可以是多个,以`,`隔开
//options:可选,配置参数
//callback:可选,回调
mongoose.connect('mongodb://数据库地址(包括端口号)/数据库名称')
mongoose.connect('mongodb://用户名:密码@127.0.0.1:27017/数据库名称')
如果你的app中要连接多个数据库,只需要设置多个url以,隔开,同时设置mongos
为true
mongoose.connect('urlA,urlB,...', {
mongos : true
})
mongoose.connect(url, options, function(error) {
});
执行下列代码后,控制台输出“连接成功”
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/test", function(err) {
if(err){
console.log('连接失败');
}else{
console.log('连接成功');
}
});
如果开启鉴权控制,以用户名"u1",密码"123456"登录'db1'数据库。执行代码后,控制台输出“连接成功”
var mongoose = require('mongoose');
mongoose.connect("mongodb://u1:123456@localhost/db1", function(err) {
if(err){
console.log('连接失败');
}else{
console.log('连接成功');
}
});
创建 config.js ,存放了 url 连接地址。
module.exports = {
mongoUrl: 'mongodb://username:password@domain:port/database',
jwtKey: 'zephyr-jwt-secret-key'
}
创建 connection.js ,复用连接。
const mongoose = require('mongoose');
const DB_URL = require("../config").mongoUrl;
mongoose.connect(DB_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("we are connected"))
.catch(error => console.log(error));
我有如下数据
创建 banner.js ,实例化模型。
const mongoose = require('mongoose');
const Banner = new mongoose.Schema({
id: Number,
title: String,
url: String,
to: String
})
module.exports = mongoose.model('Banner', Banner);
创建 query.js ,执行查询。
require('../db/connection');
const banner = require('../models/banner');
class SourceController {
// 获取首页banner
async getBanner(ctx, next) {
const res = await banner.find(function (err, result) {
if (err) return handleError(err);
console.log('ok' + result);
return result;
})
ctx.body = res;
}
}
module.exports = new SourceController();
执行 node app.js
mongoose.disconnect();