nodejs 操作mongodb

1.连接

db.js内容

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

 var assert = require('assert');

 var url = 'mongodb://localhost:27017/blog';

module.exports.DB = function (name, callback) {
mongo.connect(url, function (err, db) {
    assert.equal(null, err);
    var collection = db.collection(name);
    if (typeof collection === 'undefined') {
        db.createCollection(name);
        collection = db.collection(name);
    }
    if (typeof callback === 'function') {
        callback(db, collection);
    }
});
};

2.增加

index.js内容

var DB = require('../models/db');
DB.DB('users',function (mdb,col) {

    col.ensureIndex('name', {unique: true});
    // 写入 user 文档
    col.insert(newUser, {safe: true}, function(err, user) {
      mdb.close();
      if (err) {
        req.flash('error', err);
        return res.redirect('/reg');
      }
      //req.session.user = newUser;
      req.flash('success', '注册成功');
      res.redirect('/');
    });
  })

3.查询

index.js内容

    DB.DB('guige',function (db,collection) {
        collection.find({}).sort({time: -1}).toArray(function(err, docs) {

          db.close();

          if(err){
            conole.log(err);
          }
          else{
            console.dir(docs);
          }

        });
      })
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、付费专栏及课程。

余额充值