Node.js--使用MongoDB存储数据

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/wo_921110/article/details/78716153

MongoDB的基本使用

特点:

  • 使用BSON存储数据
  • 支持相对丰富的查询操作
  • 支持索引
  • 副本集
  • 分片
  • 无模式
  • 部署简单方便

服务的启动:

  • MongoDB运行的两种方式
  • 启动命令的使用
mongo 127.0.0.1:27017
连接指定ip地址下的27017端口
show dbs
查看数据库
db.users.insert({"username": "Sid"})
创建一个users的数据表,并且插入数据
show collection
查看当前的数据表
db.users.find()
查找当前数据表的插入数据
db.users.insert({"username": "Zoe","group": "reporter"});
为users数据表插入数据
b.users.update({"username":"Zoe"}, {$set: {"group":"writer"}});
查找到username:Zoe,并修改第一条username:Zoe的group的值
db.users.update({"username":"Zoe"}, {$set: {"group":"programmer"}},{multi: true});
查找到username:Zoe,并修改全部username:Zoe的group的值
db.users.save({"_id": ObjectId("5a2601f0fb38eba7e7b50f9e"),"group":"reporter"})
通过_id插入group:reportert,和update的区别就是只保存插入的数据,以前的数据全部清除
db.users.remove({"group": "reporter"})
删除一个group:reporter的数据
db.users.remove({"group": "reporter"},true)
删除全部group:reporter的数据
db.users.remove({})
删除文档,但是索引还在
db.users.drop()
删除文档和索引

使用Mongoose模块操作MongoDB

  • 模块介绍
  • 配置与链接
  • Model与Schema
  • 创建文档
  • 删除文档
  • 简单查询
  • 条件语句
Mogsoose:支持强类型模式也支持弱类型模式
Model与Schema:
  • Model:建立node.js中的对象和mongodb中文档对应 的功能,通过操作Model创建删除,修改,查询的mongodb语言的文档
  • Schema:实现mongoose中数据类型和结构的定义,从而在无模式的mongodb下实现模式化的存储
Model.js
var mongoose = require('mongoose');
var uri = 'mongodb://username:password@hostname:port/databasename';
uri = "mongodb://localhost/part9";

mongoose.Promise = global.Promise;  
mongoose.connect(uri,{useMongoClient: true});

var BookSchema = mongoose.Schema({
	name:String,
	author:String,
	publishTime:Date
});

mongoose.model('Book', BookSchema);
插入操作(insert.js):
var mongoose = require('mongoose');
require('./model.js');

var Book = mongoose.model('Book');

var book = new Book({
	name:"MEAN Web Development",
	author:"Green",
	publishTime:new Date()
});

book.author = 'Jim';

book.save(function(err){
	console.log('save status:', err ? 'failed' : 'success');
});
运行结果:


查询操作(find.js):
var mongoose = require('mongoose');

require('./model.js');

var Book = mongoose.model('Book');

Book.find({},function(err, docs){
	if(err){
		console.log('err:', err);
		return;
	}
	console.log('result:', docs);
});
运行结果:


查询第一个满足条件的操作(findOne.js):
var mongoose = require('mongoose');

require('./model.js');

var Book = mongoose.model('Book');

Book.findOne({author:"Jim"}, function(err, doc){
	if(err){
		console.log('err:', err);
		return;
	}
	doc.author = 'Jame';
	doc.save(); 
	console.log('findOne result:', doc)
});
运行结果:


删除操作:
var mongoose = require('mongoose');

require('./model.js');

var Book = mongoose.model('Book');

Book.findOne({author: 'Jim'}, function(err, doc){
	if(err){
		console.log('findOne err:', err);
		return;
	}

	if(doc) {
		doc.remove();
	}
});
运行结果:


查询操作:
var mongoose = require('mongoose');

require('./model.js');

var Book = mongoose.model('Book');

var cond = {
	$or: [
		{author: 'Jame'},
		{author: 'Jim'}
	]

};
Book.find(cond,function(err, docs){
	if(err) {
		console.log('find by cond err:', err);
		return;
	}

	console.log('cond:', cond, 'result:', docs)
});

运行结果:


在Express项目中使用Mongoose


  • 使用express mongooseExpress创建默认项目,然后下载到本地,在本地mongooseExpress文件夹下新建文件夹models和config
  • 在models文件夹下新建user.server.model.js,在config文件夹下新建config.jsmongoose.js
  • 在mongooseExpress文件下的route文件夹下user.js进行修改和在mongooseExpress下app.js修改(修改的地方在下面)
  • 在 mongooseExpress文件夹下使用命令cnpm install安装express和 cnpm install mongoose --save安装mongoose
  • 然后在 mongooseExpress文件夹下命令node bin/www
  • 最后Alt+Shift+t新建一个连接,通过命令curl localhost:3000/users/test查看
user.server.model.js:
var mongoose = require('mongoose');

var UserSchema = new mongoose.Schema({
	uid: Number,
	username: String,
	createTime: Date,
	loastLogin: Date
});

mongoose.model('User', UserSchema);
config.js:
module.exports = {
	mongodb: "mongodb://localhost/part9"
};
mongoose.js:
var mongoose = require('mongoose');
var config = require('./config.js');

module.exports = function(){

	mongoose.Promise = global.Promise;  
	var db = mongoose.connect(config.mongodb,{useMongoClient: true});

	require('../models/user.server.model.js');
	return db;
}
app.js中引入mongoose:
var mongoose = require('./config/mongoose.js');
var db = mongoose();
user.js中添加的蓝字:
var express = require('express');
var router = express.Router();

var mongoose = require('mongoose');
var User = mongoose.model('User');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/test', function(req, res, next){
	var user = new User({
		uid: 1,
		username: 'Sid'
	});

	user.save(function(err){
		if(err){
			res.end('Error');
			return next();
		}

		User.find({}, function(err, docs){
		if(err){
			res.end("Error");
			return next();
		}

		res.json(docs);
		});
	})
});

module.exports = router;
运行结果:




展开阅读全文

使用SharedPreferences来存储数据

12-13

AppPrefActivity.javarn[code=java]package com.selfteaching.learningpreferences;rnrnimport android.content.SharedPreferences;rnimport android.os.Bundle;rnimport android.preference.CheckBoxPreference;rnimport android.preference.EditTextPreference;rnimport android.preference.Preference;rnimport android.preference.Preference.OnPreferenceChangeListener;rnimport android.preference.Preference.OnPreferenceClickListener;rnimport android.preference.PreferenceActivity;rnimport android.preference.PreferenceManager;rnimport android.widget.Toast;rnrnpublic class AppPrefActivity extends PreferenceActivity rn private CheckBoxPreference mCheckbox=null;rn private String oldCatName;rn private EditTextPreference catName;rn private SharedPreferences.OnSharedPreferenceChangeListener listener;rn @Overridern public void onCreate(Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rn addPreferencesFromResource(R.xml.myappprefs);rn mCheckbox = (CheckBoxPreference) findPreference("checkboxPref");rn mCheckbox.setOnPreferenceClickListener(new OnPreferenceClickListener() rn @Overridern public boolean onPreferenceClick(Preference preference) rn //这里可以监听到这个CheckBox 的点击事件rn return true;rn rn );rn rn mCheckbox.setOnPreferenceChangeListener(new OnPreferenceChangeListener() rn @Overridern public boolean onPreferenceChange(Preference arg0, Object newValue) rn //这里可以监听到checkBox中值是否改变了rn //并且可以拿到新改变的值rn Toast.makeText(getBaseContext(), "改变的值为" + (Boolean)newValue, Toast.LENGTH_LONG).show();rn return true;rn rn );rn rn createListener();rn catName = (EditTextPreference) findPreference("editTextPref");rn oldCatName = catName.getText();rn rn rn private void createListener() rn listener = new SharedPreferences.OnSharedPreferenceChangeListener() rn @Overridern public void onSharedPreferenceChanged(rn SharedPreferences sharedPreferences, String key) rn String value = sharedPreferences.getString("cat_name", "NULL");rn if (value.equals("")) rn catName.setText(oldCatName);rn setPreferenceScreen(null);rn addPreferencesFromResource(R.xml.myappprefs);rn else rn oldCatName = value;rn rn rn ;rn PreferenceManager.getDefaultSharedPreferences(getApplicationContext())rn .registerOnSharedPreferenceChangeListener(listener);rn rnrnrn [/code]rnrnMainActivity.javarn[code=java]package com.selfteaching.learningpreferences;rnrnrnimport android.app.Activity;rnimport android.content.Intent;rnimport android.content.SharedPreferences;rnimport android.os.Bundle;rnimport android.view.Menu;rnimport android.view.MenuItem;rnimport android.view.View;rnimport android.view.View.OnClickListener;rnimport android.widget.Button;rnimport android.widget.EditText;rnimport android.widget.Toast;rnrnpublic class MainActivity extends Activity implements OnClickListenerrn private Button bt1=null;rn private Button bt2=null;rn private Button bt3=null;rn private EditText et=null;rn @Overridern protected void onCreate(Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rn setContentView(R.layout.activity_main);rn et=(EditText)findViewById(R.id.txtString);rn bt1=(Button)findViewById(R.id.btnPreferences);rn bt1.setOnClickListener(this);rn bt2=(Button)findViewById(R.id.btnDisplayValues);rn bt2.setOnClickListener(this);rn bt3=(Button)findViewById(R.id.btnModifyValues);rn bt3.setOnClickListener(this);rn rn rn @Overridern public void onClick(View v) rn switch (v.getId()) rn case R.id.btnPreferences:rn Intent i=new Intent("com.selfteaching.AppPrefActivity");rn startActivity(i);rn break;rn case R.id.btnDisplayValues:rn SharedPreferences appPrefs=getSharedPreferences("com.selfteaching.learningpreferences_preferences",MODE_PRIVATE);rn DisplayText(appPrefs.getString("editTextPref","str"));rn break;rn case R.id.btnModifyValues:rn SharedPreferences appPref=getSharedPreferences("com.selfteaching.learningpreferences_preferences",MODE_PRIVATE);rn SharedPreferences.Editor prefsEditor=appPref.edit();rn String str1=et.getText().toString().trim();rn prefsEditor.putString("editTextPref",str1);rn prefsEditor.commit();rn break;rn default:break;rn rn rn rn private void DisplayText(String str)rn rn Toast.makeText(getBaseContext(),str,Toast.LENGTH_LONG).show();rn rn rnrn @Overridern public boolean onCreateOptionsMenu(Menu menu) rn // Inflate the menu; this adds items to the action bar if it is present.rn getMenuInflater().inflate(R.menu.main, menu);rn return true;rn rnrn @Overridern public boolean onOptionsItemSelected(MenuItem item) rn // Handle action bar item clicks here. The action bar willrn // automatically handle clicks on the Home/Up button, so longrn // as you specify a parent activity in AndroidManifest.xml.rn int id = item.getItemId();rn if (id == R.id.action_settings) rn return true;rn rn return super.onOptionsItemSelected(item);rn rnrn [/code]rnrnactivity_main.xmlrn[code=java]rn rn rn rn rn rn rn rn rn rnrnrn [/code]rnrnmyappprefs.xmlrn[code=java]rnrn rn rn rn rn rn rn rn rn rnrn [/code]rnrnAndroidManifest.xmlrn[code=java]rnrnrn rnrn rn rn rn rnrn rn rn rn rn rn rn rn rn rn rn rn rn rn rnrnrn [/code]rnrn[img=https://img-bbs.csdn.net/upload/201612/13/1481592273_405594.jpg][/img]rn[img=https://img-bbs.csdn.net/upload/201612/13/1481592286_686862.png][/img]rn[img=https://img-bbs.csdn.net/upload/201612/13/1481592295_405140.png][/img]rn 论坛

没有更多推荐了,返回首页