Mongoose
是用来简化MongoDB数据库操作的,在node.js异步环境下对MongoDB进行便捷操作的对象模型工具。
npm install mongoose
例子:
var mongoose = require('mongoose');
var db = mongoose.connection;
//连接失败
db.on('error', console.error.bind(console, 'connection error:'));
//连接成功
db.once('open', function() {
console.log("connection success...");
});
//创建连接
mongoose.connect('mongodb://localhost/test');
var kittySchema = new mongoose.Schema({
name: String
});
//
var Kitten = mongoose.model('Kitten', kittySchema);
var silence = new Kitten({ name: 'Silence' });
//保存
silence.save(function (err) {
if(!err){
console.log("save success...");
}
})
//查询name=Silence
// Kitten.find({name:'Silence'},function (err,docs) {
// if(!err){
// console.log(JSON.stringify(docs));
// }
// })
var mongoose = require('mongoose');
var db = mongoose.connection;
//连接失败
db.on('error', console.error.bind(console, 'connection error:'));
//连接成功
db.once('open', function() {
console.log("connection success...");
});
//创建连接
mongoose.connect('mongodb://localhost/test');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});
官方文档:https://mongoosejs.com/docs/schematypes.html
类型 | 功能 |
---|---|
String | 字符串 |
Number | 数字 |
Date | 日期 |
Buffer | 二进制 |
Boolean | 布尔值 |
Mixed | 混合 |
ObjectId | 对象ID |
Array | 数组 |
Decimal128 | Decimal128 |
Map | map集合 |
例子:
var schema3 = new Schema({
test: {
type: String,
lowercase: true, // 总是将test的值转化为小写
uppercase: true, // 总是将test的值转化为大写
required:true, //设定是否必填
default:'star', //设定默认值
index:true, //设定索引值
unique:true, //索引值唯一
sparse:true, //是否启用稀疏索引
match:RegExp, //判断是否通过正则验证
enum:Array, //判断test值是否包含于enmu对应的数组中
min:Number, //判断对应值是否大于等于给定值
max:Number, //判断对应值是否小于等于给定值
trim:true //去除数据前后的空格
capped:1024 //限定大小最大为1024字节
validate:function,为此属性添加一个验证器函数,如demo1所示
get:function,//为这个属性定义一个定制的getter Object.defineProperty()。如demo2所示
set:function,//定义此属性的自定义设置Object.defineProperty()。如demo2所示
}
});
---------------------
作者:StevenDIY
来源:CSDN
原文:https://blog.csdn.net/momDIY/article/details/76285369
版权声明:本文为博主原创文章,转载请附上博文链接!
官方例子:
var schema = new Schema({
name: String,
binary: Buffer,
living: Boolean,
updated: { type: Date, default: Date.now },
age: { type: Number, min: 18, max: 65 },
mixed: Schema.Types.Mixed,
_someId: Schema.Types.ObjectId,
decimal: Schema.Types.Decimal128,
array: [],
ofString: [String],
ofNumber: [Number],
ofDates: [Date],
ofBuffer: [Buffer],
ofBoolean: [Boolean],
ofMixed: [Schema.Types.Mixed],
ofObjectId: [Schema.Types.ObjectId],
ofArrays: [[]],
ofArrayOfNumbers: [[Number]],
nested: {
stuff: { type: String, lowercase: true, trim: true }
},
map: Map,
mapOfString: {
type: Map,
of: String
}
})
// example use
var Thing = mongoose.model('Thing', schema);
var m = new Thing;
m.name = 'Statue of Liberty';
m.age = 125;
m.updated = new Date;
m.binary = Buffer.alloc(0);
m.living = false;
m.mixed = { any: { thing: 'i want' } };
m.markModified('mixed');
m._someId = new mongoose.Types.ObjectId;
m.array.push(1);
m.ofString.push("strings!");
m.ofNumber.unshift(1,2,3,4);
m.ofDates.addToSet(new Date);
m.ofBuffer.pop();
m.ofMixed = [1, [], 'three', { four: 5 }];
m.nested.stuff = 'good';
m.map = new Map([['key', 'value']]);
m.save(callback);
schema:mongoose数据表存储的模型
//定义数据模型
var User = mongoose.model('User', user);
官方文档:https://mongoosejs.com/docs/api.html#Model
var mongoose = require("mongoose")
//监听连接
var db = mongoose.connection;
//连接失败
db.on('error', console.error.bind(console, 'connection error:'));
//连接成功
db.once('open', function() {
console.log("connection success...");
});
//创建连接
mongoose.connect('mongodb://localhost/test')
//定义文档规则
var user = new mongoose.Schema({
name: String,
age: Number,
time:{
type: Date,
default: Date.now
}
});
//定义数据模型
var User = mongoose.model('User', user);
//保存50人
for(i=0;i<50;i++){
var user = new User({
name: "zhangsan" + i,
age: 5 + i,
});
user.save(function (err) {
if(!err){
console.log("save success...");
}
})
}
User.update({_id: '5bdbc1bef86c720764055f06'}, { $set: { age: 100 }},function (err,tank) {
console.log(tank);
})
User.deleteMany({_id: '5bdbc1bef86c720764055f06'},function (err) {
console.log("delete success...");
})
Kitten.remove({
name: 'Silence2'
},function (err,ret) {
if(err){
console.log(err);
}else{
console.log(ret);
}
})
User.find({_id: '5bdbc1bef86c720764055f06'},function (err,data) {
console.log(data);
})
//查找所有,并按照时间排序
User.find({}).sort({time : 'desc'}).exec(function (err,data) {
console.log(data);
})
var mongoose = require("mongoose")
//监听连接
var db = mongoose.connection;
//连接失败
db.on('error', console.error.bind(console, 'connection error:'));
//连接成功
db.once('open', function() {
console.log("connection success...");
});
//创建连接
mongoose.connect('mongodb://localhost/test')
//定义文档规则
var user = new mongoose.Schema({
name: String,
age: Number,
time:{
type: Date,
default: Date.now
}
});
//定义数据模型
var User = mongoose.model('User', user);
//保存50人
// for(i=0;i<50;i++){
// var user = new User({
// name: "zhangsan" + i,
// age: 5 + i,
// });
// user.save(function (err) {
// if(!err){
// console.log("save success...");
// }
// })
// }
//查找
// User.find({_id: '5bdbc1bef86c720764055f06'},function (err,data) {
// console.log(data);
// })
//修改
// User.update({_id: '5bdbc1bef86c720764055f06'}, { $set: { age: 100 }},function (err,tank) {
// console.log(tank);
// })
//删除
// User.deleteMany({_id: '5bdbc1bef86c720764055f06'},function (err) {
// console.log("delete success...");
// })