MONGO basic use, and use of mongoose in Express projects

Source: Internet
Author: User
Tags findone install node

MongoDB's basic use of MongoDB features:
    • Storing data using Bson
    • Supports relatively rich query operations (relative to other NoSQL databases)
    • Support Index
    • Replica set (supports multiple instances/multiple servers running the same database)
    • Sharding (Database horizontal scaling)
    • Modeless (data in the same data document can be different)
    • Easy Deployment (no password by default, also security issues)
Start of service:
Mongod

(You need to install the MONGO database and create a directory of MongoDB: $ mkdir-p/data/db)

After you start MongoDB, you can use the MONGO command line to manipulate the database, or use a GUI client such as Robomongo.

MONGO Command line tool operation MongoDB:

Use a database: (MongoDB does not need to create a database in advance and is created automatically when writing to a database)

$ use MyTest

Insert Data :(Inserts a document into the Users collection under the MyTest database)

$ db.users.insert ({"username": "Nuanfeng"})

You can then view the databases and collections:

$ show dbs$ Show collections

To view all documents in the Users collection:

$ db.users.find ()

Add another piece of data: (MongoDB is modeless, so you can add data in different formats)

$ db.users.insert ({"username": "Zoe", "Group": "Reporter"})

Then use Db.users.find () to view, as follows:


To view the number of data:

$ db.users.find (). Count ()

query data by ID:

$ db.users.find ({"_id": ObjectId ("584bc73ea635e489676cf5db")})

Update data: (Match to the first article)

$ db.users.update ({"username": "Zoe"}, {$set: {"group": "Writer"}})

Update data: (all matching to)

$ db.users.update ({"username": "Zoe"}, {$set: {"group": "Writer"}}, {multi:true})

The data can also be modified with Save (): (Must be based on ' _id ', will replace the original data directly)

Db.users.save ({"_id": ObjectId ("584bc73ea635e489676cf5db"), "group": "Reporter"})

Delete All that meet the criteria:

$ db.users.remove ({"Group": "Reporter"});

Delete the first rule that satisfies the condition:

$ db.users.remove ({"Group": "Reporter"}, true);

To delete all the documents in the collection:

$ db.users.remove ({})

Delete Entire collection (all documents and indexes)

$ db.users.drop ()

Introduction to using the Mongoose module to manipulate MongoDB modules

Mongoose is a module that corresponds to a Nodejs object and a document in MongoDB.

The mongoose supports both strong mode and modeless mode.

Install Mongoose:

$ NPM Install Mongoose

Let's look at the final directory structure:

Configuration and Links

The format of the link: (You can also omit the user name, password, port number)

var uri = ' mongodb://username:[email protected]:p ort/databasename 'mongoose.connect (URI);
Model and Schema

Model makes the Nodejs object and the document in MongoDB correspond, theSchema realizes the model data type and the structure definition, thus realizes the pattern storage in the modeless MongoDB.

Model.js

/* * Configure and link MongoDB * */ var mongoose = require (' Mongoose '); var uri = ' mongodb://localhost/mongoose-base '; Mongoose.connect (URI); /* * Create SCHEMA, create model * */ var New Mongoose. Schema ({    name:string,    author:string,    publishtime:date}); Mongoose.model (' book ', Bookschema) ;
Create a document

Insert.js

varMongoose = require (' Mongoose ')); require ('./model.js ');/** Get model, create instance of book Entity **/varBook = Mongoose.model (' book ');varBook =NewBook ({name:' MEAN Web Develop ', Author:' Green ', Publishtime:NewDate ()}); Book.author= ' Jim ';//parameters can be re-specified/** Insert Data **/Book.save (function(ERR) {//perform the Save and view the return statusConsole.log (' Save status: ', err? ' Failed ': ' Success ');})
Simple query

Find.js

var mongoose = require (' Mongoose '); require ('./model.js '); var Book = Mongoose.model (' book '); /* * Query all data * */  function(err, Docs) {  if  (err) {    console.log (' err: ' ) , err);     return ;  }  Console.log (Docs)})

Findone.js

var mongoose = require (' Mongoose '); require ('./model.js '); var Book = Mongoose.model (' book '); /* * Query One piece of data and modify * */  function(err, doc) {  if  (err) {    console.log (' err: ' ) , err);     return ;  }   = ' James ';  Doc.save ();  Console.log (' findOne result: ', Doc)})
Delete a document

Remove.js

var mongoose = require (' Mongoose '); require ('./model.js '); var Book = Mongoose.model ("book"function(err, doc) {  if  (err) {    Console.log (' findOne err: ', err);     return ;  }   if (DOC) {    doc.remove ();  }})
Conditional statements
var mongoose = require (' Mongoose '); require ('./model.js '); var Book = Mongoose.model (' book '); var cond = {    $or: [        ' Jim '},        ' James '}    function (Err, Docs) {    if(err) {        console.log (' Find by cond err: ', err);    }    Console.log (' cond: ', cond, ' Result: ', Docs);})

Use Mongoose to quickly generate express applications in Express projects

Here we use Express-generator to quickly generate express applications (first install node, NPM, Express-generator, MongoDB)

$ Express Mongooseexpress

First look at the final project chart:

Configure the database and connect

Create a new config folder to place database configuration information

Config/config.js

Module.exports = {    ' mongodb://localhost:27017/mongoose-test '}

Config/mongoose.js

var mongoose = require (' Mongoose '); var config = require ('./config.js 'function() {    var db =  Mongoose.connect (CONFIG.MONGODB);    Require ('.. /models/user.server.model.js ');     return DB;}
Global introduction of Mongoose

Refer to the Mongoose configuration information you just created (8, 92 lines) before the App.js routing module

1 varExpress = require (' Express ');2 varPath = require (' path ');3 varFavicon = require (' Serve-favicon '));4 varLogger = require (' Morgan ');5 varCookieparser = require (' Cookie-parser '));6 varBodyparser = require (' Body-parser '));7 8 varMongoose = require ('./config/mongoose.js '));9 vardb =Mongoose ();Ten  One varindex = require ('./routes/index ')); A varUsers = require ('./routes/users ');
Create schema and model

New Models Folder

/models/user.server.model.js

var mongoose = require (' Mongoose '); var New Mongoose. Schema ({    uid:number,    username:string,    createtime:date,    lastlogin:date}); Mongoose.model (' User ', Userschema);
Writing Database processing logic code

We add the code of the database access operation directly in the Users routing module

/routes/users.js

1 varExpress = require (' Express ');2 varRouter =Express. Router ();3 4 varMongoose = require (' Mongoose '));5 varuser = Mongoose.model (' user ');6 7 /*GET users listing.*/8Router.get ('/',function(req, res, next) {9Res.send (' respond with a resource ');Ten }); One  ARouter.get ('/test ',function(req, res, next) { -     varuser =NewUser ({ -Uid:1, theUsername: ' Nuanfeng ' -     }) -  -User.save (function(err) { +         if(err) { -Res.end (' Error '); +             returnnext (); A         } at  -User.find ({},function(Err, docs) { -             if(err) { -Res.end (' Error '); -                 returnnext (); -             } in  - Res.json (docs); to         }) +     }) - }) the  *Module.exports = router;
Run node View effect
$ node Bin/www

Then access in the browser: http://localhost:3000/users/test, you can store a record in the database, and return its JSON data on the current page

MONGO basic use, and use of mongoose in Express projects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.