美文网首页程序员
node的Mongodb使用(mongoose)

node的Mongodb使用(mongoose)

作者: stutterr | 来源:发表于2017-12-03 21:49 被阅读149次

1. 首先安装模块mongoose

运行npm i mongoose

2. 添加数据库连接配置文件config/default.js

'use strict'
const db = require('mongoose')
const DB_URL = 'mongodb://localhost:27017/myblog'
db.Promise = global.Promise
db.connect(DB_URL, {
   useMongoClient: true,
   /* other options */
})
db.connection.once('connected', function () {
   console.log("connected mongoodb!")
})
db.connection.on('error', function () {
  console.log('connect error')
})
db.connection.on('disconnected', function () {
   console.log('Mongoose connection disconnected')
})

module.exports = db

3. 编写model模块,以user为例

const mongodb = require('../config/default.js')
const Schema = mongodb.Schema

let userItem = {
   name: String,
   password: String
}


let userSchema = new Schema(userItem)
userSchema.set('collection', 'user')

let userModel = mongodb.model("user", userSchema)

module.exports = userModel

schema是mongoose里会用到的一种数据模式,可以理解为表结构的定义;每个schema会映射到mongodb中的一个collection,它不具备操作数据库的能力

model是由schema生成的模型,可以对数据库的操作

这里userItem为为数据库表结构的通过Schema对象来建立与数据库的映射,之后将生成的userSchema Schema对象通过mongoose的方法来生成可操作的持久化对象

let userModel = mongodb.model("user", userSchema)

这里第一个参数为数据库中的集合名(sql中的表名)
之后就可以通过userModel来进行增删改查操作

ps:
需要注意的是userSchema.set('collection', 'user')这句
当我们忽略掉这句时,当对数据库进行写入操作, 能够写入成功,但是却多了一>个加了s的集合 ,即users集合,原集合没有变化

官方文档解释

When no collection argument is passed, Mongoose produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. If you don’t like this behavior, either pass a collection name or set your schemas collection name option.

译文:当没有传入collection参数时,Mongoose会通过model name(就是第一个参数),调用utils.toCollectionName方法产生一个collection name,而这个方法会使name变成复数形式。如果你不想要这个过程,只要传入collection name参数或设置Schema中的collection name选项。

所以需要做如下操作

// or

schema.set('collection', 'user')

//or
var collectionName = 'user'
var M = mongoose.model('Actor', schema, collectionName)

4. 编写test.js文件测试

const User = require('./user.js')

function inset() {
    let user = new User({
        name: "mavin",
        password: "333"
    })
    user.save(function (err, res) {
        if (err) {
            console.log("ERROR" + err)
        } else {
            console.log("RES " + res)
        }
    })
}


function update() {
    var wherestr = { 'name': 'mavin' }
    var updatestr = { 'password': 'zzz' }  

    User.update(wherestr, updatestr, (err, res) => {
        if (err) {
            console.log("ERROR" + err)
        } else {
            console.log(res)
        }
    })
}

function remove() {
    User.remove(wherestr, function (err, res) {
        if (err) {
            console.log("error" + err)
        } else {
            console.log(res)
        }
    })
}

// 分页查询
function getByPager(){
    
    var pageSize = 5;                   //一页多少条
    var currentPage = 1;                //当前第几页
    var sort = {'logindate':-1};        //排序(按登录时间倒序)
    var condition = {};                 //条件
    var skipnum = (currentPage - 1) * pageSize;   //跳过数
    
    User.find(condition).skip(skipnum).limit(pageSize).sort(sort).exec(function (err, res) {
        if (err) {
            console.log("Error:" + err);
        }
        else {
            console.log("Res:" + res);
        }
    })
}

getByPager()

inset()

test.js文件目录执行

node test.js

相关文章

网友评论

    本文标题:node的Mongodb使用(mongoose)

    本文链接:https://www.haomeiwen.com/subject/vumzbxtx.html