A useful API for databases is Mongoose. In Node development, the underlying layer handles more of the details. Speed up development and maintain less code.

Start the mongodb server and establish the mongodb connection

Install the mongoose
npm install mongoose
Copy the code
Establish a connection
var mongoose = require('mongoose'Var db = mongoose. Connect ('mongodb://localhost/tasks'Schema var schema = mongoose.Schema var Tasks = new schema ({project: String, description: String}) // Use schma to drive mongoose.'Task', Tasks)
var Task = mongoose.model('Task'Var task = new task () var task = new task ()'Task', Tasks)
Copy the code
Add the project
One entry: task.project ='bikeshed'
 task.description = 'do you know the mongoose'
 task.save(function(err) {
    if (err) throw err;
    console.log('task saved'Var taskArr = new task () : var taskArr = [{project:'00', description: '00'}, {project: '11', description: '11'}] // save task.collection.insert(taskArr, onInsert)function onInsert(err, taskArr) {
    if (err) throw err;
    console.log('task saved array')
 }
 
 or
 
 task.create(taskArr, function(err, small) {
    if (err) throw err;
    console.log('task saved array create')})Copy the code
Query project
var Task = mongoose.model('Task', Tasks)

Task.find({'project':'00'}, function(err, tasks) {
   for (var i = 0; i < tasks.length; i++) {
     console.log('id' + tasks[i]._id);
     console.log(tasks[i].description)
   }
})
Copy the code
Update project
var Task = mongoose.model('Task'Update ({_id: Tasks);'XXXX'}, {description: 'XXX'}, {multi:false})
Copy the code
Delete the project
var Task = mongoose.model('Task');

Task.findById('XXXXXX'.function(err, task) {
  task.remove()  
})
Copy the code