mongoose

mongoose查询没有响应

月盾
使用mongoose建立了连接以后,通过model查询数据,如:testModel.find(),既不报错又不返回数据。 const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_database'); 使用mongoose.connect连接产生在mongoose.connection上,使用mongoose.createConnection是反回一个连接对象,建立model的时候需要使用这个连接才有效,此时使用mongoose.model是无效的。 const conn = mongoose.createConnection('your connection string'); const MyModel = conn.model('ModelName', schema); const m = new MyModel; m.save(); // 可以工作 vs const conn = mongoose.createConnection('your connection string'); const MyModel = mongoose.model('ModelName', schema); const m = new MyModel; m.save(); // 不能工作

open() is deprecated in mongoose >= 4.11.0, use openUri()

月盾
`open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials. 修改连接参数: url = `mongodb://${this.username}:${this.password}@${this.host}:${this.port}/${this.dbName}`; const opts = { // autoReconnect: false,//默认true // reconnectTries: 30,//尝试重连,默认30次 // reconnectInterval: 1000, //重连间隔,默认1000毫秒 loggerLevel: "warn", //error/warn/info/debug useMongoClient: true }; mongoose.

mongoose自动添加createdAt和updatedAt

月盾
export var CommentSchema: Schema = new Schema({ Id: String, content: String, status: { type: Boolean, default: true } }, { timestamps: true}); 添加{ timestamps: true}选项即可,如果需要自定义属性名称可以直接指定: { timestamps: {createdAt:'created_at', updatedAt:'updated_at'}}

Mongodb和mongoose模糊查询

月盾
需求说明:在mongdb中使用模糊查询,就像sql中的like查询,在where条件中使用模糊匹配,当然最重要的是需要模糊查询的字符串是动态传入的 以一篇文章为例,content字段为文章内容,我们要查询文章内容中包含Nodejs关键字的文章 mongodb中查询 select * from articles where content like '%Nodejs%'; db.articles.find( { content: /Nodejs/i } ) Article.find({ content: /Nodejs/i}, function (err, docs) {}); 这种写法是一种简写操作,需要注意的是不能带双引号,带了双引号就成了字符串。但是这种写法是用/包裹了一个字符串类型的关键字,在实际程序是动态传入的,比如: var a="Nodejs" ; Article.find({ content: /a/i}, function (err, docs) {}); 此时会把"a"当做要查询的关键字而不是"Nodejs",所以这时还是需要用到完整的查询方式,就是使用$regex关键字,还有$options选项 var text = 'Nodejs';//动态传入的变量 Article.find({ content: { $regex: text, $options: 'i' }}, function (err, docs) {}); $options选项值: i 大小写不敏感 m $regex包含正则^,$符号的表达式 x 忽略空格 s 允许逗点匹配所有字符串 其实$regex就是正则表达式的写法 查找数组中的字段: contacts:{ [ { address: "address1", name: "张三" }, { address: "address2", name: "李四" }, .

Mongodb和mongoose聚合查询

月盾
mongdb查询某一字段sum值 需求说明:articles有一个字段pv记录了该文章的访问量,现在要统计所有文章访问量,类似于sql中的sum统计 mongodb中查询 select sum(pv) from articles; db.articles.aggregate([{$group:{_id:null,pv:{$sum:"$pv"}}}]); 结果:{ "_id" : null, "pv" : 2 } select sum(pv) from articles where createDate <= '2016-10-20'; db.articles.aggregate([{$match:{createDate:{$lte:"2016-10-20"}}},{$group:{_id:null,pv:{$sum:"$pv"}}}]); 结果:{ "_id" : null, "pv" : 9 } select sum(pv) from articles where category = 'Nodejs'; db.articles.aggregate([{$match:{category:"Nodejs"}},{$group:{_id:null,pv:{$sum:"$pv"}}}]); 结果:{ "_id" : null, "pv" : 7 } 需要注意$match和$group的顺序,反了是不行的,因为这是Aggregation Pipeline(管道流) mongoose实现方式,与上面sql的顺序对应: Article.aggregate({ $group: { _id: null, pvCount: { $sum: '$pv' }}}, function(err, doc) { console.log("1", doc); }); Article.aggregate([{$match:{createDate:{$lte:"2016-10-20"}}},{$group:{_id:null, pvCount:{$sum:"$pv"}}}], function(err, doc) { console.

mongoose实现翻页

月盾
随着吐槽的内容越来越多,单页显示就显得不够文雅了,分页功能是一个完整系统必备的。所以就决定加上这个功能,不过分页实现起来并不容易,找了下前辈们的资料,感觉都很复杂,所以还是实现一个简单翻页好了,就是只有上一页,下一页这样简单的功能。 首先看下mongoose API,find方法源码: Model.find = function find (conditions, fields, options, callback){ if("function"==typeof conditions){ callback = conditions; conditions ={}; fields = null; options = null; }elseif("function"==typeof fields){ callback = fields; fields = null; options = null; }elseif("function"==typeof options){ callback = options; options = null; } // get the raw mongodb collection object var mq =newQuery({}, options,this,this.collection); mq.select(fields); if(this.schema.discriminatorMapping &amp;&amp; mq._selectedInclusively()){ mq.select(this.schema.options.discriminatorKey); } return mq.find(conditions, callback); }; 其中有4个参数,find(条件,需要查询的字段,选项,回调),这样看着太抽象,来一段实际应用的代码: router.get("/admin/blogList", function(req, res) { var user = req.