mongoose
Posted ruange
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mongoose相关的知识,希望对你有一定的参考价值。
1.安装monogoose
npm install mongoose -D
2.导入monogoose模块
var mongoose = require (' mongoose ');
3.连接数据库
mongoose.connect(' mongodb://主机名/数据库名称 ',( error ){
if( error ) throw error
console.log(' database connect success ')
})
4.储存数据步骤
1.定一个Schema骨架
var schema = mongoose.Schema();
var studentsSchema = new schema({
name:String,
age:Number,
set:String
})
2.创建骨架模型
var studentsModel = mongoose.model(' students ',studentsSchema); //students --集合名称
3.创建实例
var studentsInstance = new studentsModel();
接下来就是数据库的增删该查
增
studentsInstance.name = 'mogoose';
studentsInstance.age = 18;
studentsInstance.set = 'men';
studentsInstance.save(( error )=>{
if( error ) throw error
console.log(' data save success ')
})
删
studentsModel.find({ age:18 },( error,result )=>{
if( !error ){
let id = result[0]._id;
studentsModel.findByID(id,( error,docs ){ //docs -- 文档
if( !error ){
docs.remove(()=>{
console.log('delete data success')
})
}
else{
throw error
}
})
}
else{
throw error
}
})
改
stuentsModel.find({name:'mogoose'},( error,res ){
if( !error ){
let id = res[0]._id;
studentsModel.findByID( id,(error,docs){
docs.name = adminMongo;
docs.save(( error )=>{
if( !error ){
console.log(' data updata success ')
}
else{
throw error
}
})
})
}
else{
throw error
}
})
查
studentsModel.find({set:'men'},( error,data ){
if( !error ){
console.log(data);
console.log(' data find success ')
}
else{
throw error
}
})
以上是关于mongoose的主要内容,如果未能解决你的问题,请参考以下文章
ionic 实现类似于JQuery的AutoComplete
Mongoose 报错代码 (node:10256)(node:13604)(node:13604) DeprecationWarning: Mongoose: findOneAndUpdate()