使用mongoose操作mongoDB
mongoDB是无模式的,mongoose是既可以支持无模式也可以支持有模式。
创建model:
const mongoose = require(‘mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost/Mongoose');
const BookSchema = new mongoose.Schema({
Name:String,
Author:String,
PublishTime:Date
});
module.exports = mongoose.model(‘Book',BookSchema);
*:注意这里可能会出现问题:(node:4104) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html;
此时可以使用bluebird实现的promise替代:
mongoose.Promise = require(‘bluebird’);
插入操作:
const mongoose = require('mongoose');
require('./models.js');
const Book = mongoose.model('Book');
const book = new Book({
Name:'Web Development',
Author:'James',
PublishTime:new Date()
});
//book.Author = 'Curry';
book.save(err=>{
console.log('save ',err ? 'falied' : 'success');
});
查询操作:
const mongoose = require('mongoose');
require('./models.js');
const book = mongoose.model('Book');
book.find({},(err,docs)=>{
if (err) console.log(err);
console.log(docs);
});
条件查询操作:
/**
* Created by w on 2017/4/20.
*/
const mongoose = require('mongoose');
require('./models');
const book = mongoose.model('Book');
const conditions = {
$or: [{Author: 'James'},
{Author:'Curry'}]
};
book.find(conditions,(err,docs)=>{
if (err) console.log(err);
console.log(docs);
});