1. 程式人生 > >mongodb學習筆記(3)--mongoose實現curd

mongodb學習筆記(3)--mongoose實現curd

簡介

mongoose實現curd

初始化

clipboard.png

npm init
cnpm install mongoose --save-dev

index.js

const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/test97');

const UserSchema = mongoose.Schema({
    name:String,
    age:Number,
    create_at:{
        type:Date,
        default:Date.now()
    },
    isShow:{
        type:Boolean,
        default:true
    }
})

const User = mongoose.model('User',UserSchema,'user');
module.exports = User;

inser.js

const User = require('./index.js');

let newUser = new User({
    name:"jie",
    age:20,
})

newUser.save().then(result => {
    console.log(result)
})
.catch(error => {
    console.log(error)
})

clipboard.png

find.js

const User = require('./index.js');

User.find().then(result => {
    console.log(result)
})
.catch(error => {
    console.log(error)
})

clipboard.png

update.js

const User = require('./index.js');

User.updateOne({"name":"biao"},{
    age:300
}).then(result => {
    console.log(result)
})
.catch(error => {
    console.log(error)
})

clipboard.png

delete.js

const User = require('./index.js');
User.deleteOne({"name":"biao"}).then(result => {
    console.log(result)
})
.catch(error => {
    console.log(error)
})

clipboard.png