var DBUtil=function(mess,name,from){ <span style="white-space:pre"> </span>this.mess=mess;<span style="white-space:pre"> </span> <span style="white-space:pre"> </span>this.from=from; <span style="white-space:pre"> </span>this.name=name; } DBUtil.prototype.setMess=function(mess){ <span style="white-space:pre"> </span>this.mess=mess; } DBUtil.prototype.setFrom=function(from){ <span style="white-space:pre"> </span>this.from=from; } DBUtil.prototype.setName=function(name){ <span style="white-space:pre"> </span>this.name=name; } DBUtil.prototype.insert=function(db,collection){ <span style="white-space:pre"> </span>var data={name:this.name,unread:[{from:this.from,mess:[this.mess]}]}; <span style="white-space:pre"> </span>console.log(data); <span style="white-space:pre"> </span>db.collection(collection,function(err, collection) { collection.insert(data, function(err, docs) { if (err) { console.log(err); return; } }); }); } DBUtil.prototype.update=function(db,collection){ var name=this.name; var from=this.from; var mess=this.mess; var query={name:name,'unread.from':from}; var data={'unread.$.mess':mess}; console.log(this.mess); <span style="white-space:pre"> </span>db.collection(collection,function(err, collection) { collection.update(query,{$push:data},{upsert:true}, function(err, docs) { if (err) { console.log(err); return; } if(!docs){ query={name:name}; data={unread:{from:from,mess:[mess]}}; console.log(mess); collection.update(query,{$push:data},function(err, docs) { if (err) { console.log(err); return; } }); } }); }); } DBUtil.prototype.getUnRead=function(db,collection,callback){ <span style="white-space:pre"> </span>var query={name:this.name}; <span style="white-space:pre"> </span>db.collection(collection,function(err, collection) { collection.find(query).toArray(function(err,docs){ <span style="white-space:pre"> </span>callback(docs); }); }); } DBUtil.prototype.remove=function(db,collection,callback){ var query={name:this.name}; db.collection(collection,function(err, collection) { collection.remove(query,function(error){ if (err) { console.log(err); return; } }); }); } var dbutil=new DBUtil(); module.exports=dbutil;
对应json格式,_id不包含:
{ "name": "test", "unread": [ { "from": "test1", "mess": [ "这是第一条", "这是第二条", "这是第三条" ] }, { "from": "test2", "mess": [ "这是第一条", "这是第二条", "这是第三条" ] } ] }
update中,表示不存在则插入
{upsert:true, w: 1}
下载地址:http://download.csdn.net/detail/zbuger/8888039