nodejs使用mongodb,api分析

在nodejs中使用mongodb是一件很愉快的事情。

安装依赖模块

npm install --save mongodb

下面,我们来体验一些常用的api


创建连接

var MongoClient = require('mongodb').MongoClient;

var url = 'mongodb://127.0.0.1:27017/learn';
MongoClient.connect(url, function(err, db) {
    if (err)
    {
        console.log("the err is:");
        console.log(err);
    }
    else
    {
        console.log("connect success!");
    }
});
记住线上环境把mongodb放在防火墙后面,如果你在本地的27017端口起了mongodb的监听的话,会看到如下信息

connect success!


nodejs的mongodb已经帮你做了很多事啦,首先,你不再需要自己创建一个连接池(像mysql、oracle),因为驱动已经帮你做了。

获取Collection

我们可以从db对象,拿到collection对象,如下

var col = db.collection("test_col");


查看源文件,我们可以发现此方法的详细参数如下

Db.prototype.collection = function(collectionName, options, callback) {...}

options有很多详细的配置,还可以传callback函数,详细的,读者可以自己在下载好的mongodb驱动文件夹中查看,db.js

mongodb是文档开放型的,如果test_col不存在,而你又没配置options中的相关参数的话,它是不会报错的,而且,它会很正常的运行,就像test_col存在一样。

保存记录

拿到了collection,调用save就可以保存记录
var obj = {_id:1, name:"test1", createTime:new Date().getTime(), version:0};
    col.save(obj, [], function(err, data){
        console.log(err);
        console.log(data);
    });

mongodb中的默认主键是_id,而不是id,如果我们的obj没有定义_id字段的话,mongodb会给我们自动加一个,而且类型是内置的ObjectId,所以还是自己定义一个吧,别偷懒。version字段一般也是必须的,因为mongodb没有事务的概念,数据的版本管理就必不可少。
正常情况下,我们会看到如下输出
null
1
err为null,表示没发生错误,data为1,表示我们影响的数据条数为1。

查找记录

查找记录,需要使用find方法,参数有点多,我们先看驱动中的定义

/* 
* @param {Object|ObjectID} query query object to locate the object to modify
 * @param {Object} [options] additional options during update.
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the find method or null if an error occured.
 * @return {Cursor} returns a cursor to the query
 * @api public
 */
Collection.prototype.find = function() { return query.find; }();

下面这一句是什么意思呢
return query.find; 

哈哈,这又是nodejs的一个非常丰富的知识点,也是nodejs的魅力所在,addons,用C或者C++实现的自定义模块,这也是我更喜爱nodejs的原因之一。在后面的章节我会详细介绍addons,现在你只要理解它是自定义模块就好了。

官方的这几个param的注释其实让人很费解,但是它上面还又说明,我们直接看说明

* Various argument possibilities
 *  - callback?
 *  - selector, callback?,
 *  - selector, fields, callback?
 *  - selector, options, callback?
 *  - selector, fields, options, callback?
 *  - selector, fields, skip, limit, callback?
 *  - selector, fields, skip, limit, timeout, callback?
也就是说,有这些参数模式。
selector, fields, options
是最常用的一种模型。

看例子
var cond = {};  //条件
    var cols = {};  //要选择的列
    var cursor = col.find(cond, cols, []);
    cursor.toArray(function(err, data){
        console.log(err);
        console.log(data);
    });

我们给了
selector, fields, options
三个参数,然后拿到了游标(cursor),调用游标的toArray方法,输出如下

null
[ { _id: 1, name: 'test1', createTime: 1416989918758, version: 0 } ]

非常好,我们找到了刚才保存的记录。关于cond的表达式,这个内容比较多,在以后的章节中详述。

更新记录

我们要使用update方法,同样,先看官方的定义
 * @param {Object} selector the query to select the document/documents to be updated
 * @param {Object} document the fields/vals to be updated, or in the case of an upsert operation, inserted.
 * @param {Object} [options] additional options during update.
 * @param {Function} [callback] must be provided if you performing an update with a writeconcern
 * @return {null}
 * @api public
 */
Collection.prototype.update = function() { return core.update; }();
selector就是我们的条件(所谓的选择器),第二个是更新表达式,第三个options,第四个回调函数。
那要把_id为1的记录的name字段的值更新为test001,并且数据的版本+1,我们应该怎么做呢?看代码

var cond = {_id:1};  //条件
    var ups = {$set:{name:'test001'}, $inc:{version:1}};  //更新表达式
    col.update(cond, ups, [], function(err, data){
        console.log(err);
        console.log(data);
    });

输出

null
1
读者可以再用find语句自己查询,查看是否更新成功。

先写到这吧,下回再补充findAndModify,findAndRemove,remove

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Node.js提供了许多不同的方式来操作MongoDB数据库。以下是其中一些常见的方法: 1.使用官方的MongoDB Node.js驱动程序 可以使用官方的MongoDB Node.js驱动程序来连接和操作MongoDB数据库。这个驱动程序提供了许多不同的方法和选项,可以满足不同的需求。以下是一个简单的例子,展示如何使用官方驱动程序连接到MongoDB数据库,并执行简单的查询操作: ``` const MongoClient = require('mongodb').MongoClient; // 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) { console.log("Connected successfully to server"); const db = client.db(dbName); // Find some documents db.collection('users').find({}).toArray(function(err, docs) { console.log("Found the following records"); console.log(docs); client.close(); }); }); ``` 2.使用Mongoose库 Mongoose是一个MongoDB对象模型工具,它提供了一种更简单的方式来操作MongoDB数据库。它允许您定义模式和模型,以便更轻松地执行常见的操作,如插入、更新和查询文档。以下是一个例子,展示如何使用Mongoose连接到MongoDB数据库,并定义一个简单的用户模型: ``` const mongoose = require('mongoose'); // Connection URL const url = 'mongodb://localhost:27017/myproject'; // Connect to the database mongoose.connect(url, {useNewUrlParser: true}); // Define a schema const userSchema = new mongoose.Schema({ name: String, email: String, age: Number }); // Define a model const User = mongoose.model('User', userSchema); // Create a new user const user = new User({ name: 'John Smith', email: 'john@example.com', age: 30 }); // Save the user to the database user.save(function(err) { if (err) throw err; // Find all users User.find(function(err, users) { if (err) throw err; console.log(users); mongoose.connection.close(); }); }); ``` 3.使用第三方库 除了官方驱动程序和Mongoose之外,还有许多其他的Node.js库可以用于操作MongoDB数据库。一些流行的库包括MongoDB Native、mongojs和Monk。这些库提供了不同的API和功能,可以满足不同的需求。以下是一个例子,展示如何使用mongojs库连接到MongoDB数据库,并执行简单的查询操作: ``` const mongojs = require('mongojs'); // Connection URL const url = 'mongodb://localhost:27017/myproject'; // Connect to the database const db = mongojs(url, ['users']); // Find all users db.users.find(function(err, users) { if (err) throw err; console.log(users); db.close(); }); ``` 无论您选择使用哪种方法,Node.js提供了许多选项和库,可以帮助您轻松地操作MongoDB数据库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值