
friend:{
name:{type:String,required:true},
group:[{
groupName:String,
list:[{name:String}]
}]
}
假设现在数据库中的friend表中包含:
{
name:"John",
group:[
{"friends",[...]}
...
]
}
现在我要删除john的名为friends的group,那么可以用$pull来实现删除数组中的指定元素:
Friend.update({name:uname},{$pull:{"group:{groupName:"friends"}}},function(err){
if(err){
res.send(500)
console.log(err)
}
})
其中Friend是与上面的schema对应的model,这样就完成了数组对应元素的删除。如果要添加元素的话,用到的就不是$pull而是$addToSet,语法还是一样的。
与使用连接字符串的方法比较相似,如下为mongoose连接localhost上的words数据库var mongoose = require(‘mongoose’)
mongoose.connect('mongodb://localhost/words')
该链接可用mongoose模块的disconnect()方法关闭。
很多nodejs的新手都是直接用mongodb本身直接 *** 作数据库,我之前也是如此不知道大家有没有遇到过这个错误:
Error: db object already connecting, open cannot be called multiple times
也许你会说是异步写得不好,但是就算异步写得再好,也逃避不了这个错误
因为无论如何,都要用到db.open()这东西,而且访问完毕还得db.close()
于是就有一个问题:刷新得太快,或者多个用户同时访问数据库,数据库没来得及关闭,那个Error就会出现
可以做一下实验,在访问数据库的页面按住F5,就会很容易看到在页面上或者控制台上抛出的Error勒
用mongoose就不会出现这错误勒,因为一旦连接好数据库,db就会处于open状态,不存在访问时要打开,然后又要关闭的规则,然后我果断把所有mongodb部分改为mongoose,按住F5毫无压力啊,而且尼玛代码又短了一大截!
前后代码对比一下:
之前每次 *** 作要open:
User.get = function get(username, callback) {
mongodb.open(function(err, db) {
if (err) {
return callback(err)
}
//读取 users 集合
db.collection('users', function(err, collection) {
if (err) {
mongodb.close()
return callback(err)
}
//查找 name 属性为 username 的文档
collection.findOne({name: username}, function(err, doc) {
mongodb.close()
if (doc) callback (err, doc)
else callback (err, null)
})
})
})
}
现在,建立好mongoose对象模型后只需几行代码即可实现相同的功能:
User.get = function get(username, callback) {
users.findOne({name:username}, function(err, doc){
if (err) {
return callback(err, null)
}
return callback(err, doc)
})
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)