mongodb数据库插入内容文档insert方法:
var user = {
name : 'kong',
age : 18,
sex : 'man'
};
//连接数据库
mongodb.open(function(err, db){
if(err){
return false;
}
//选择users集合
db.collection('users',function(err, collection){
if(err){
mongodb.close();
return false;
}
//插入文档
collection.insert(user,{safe : true},function(err, result){
if(err){
mongodb.close();
return false;
}
//成功后返回的结果
console.log(result);
mongodb.close();
})
})
})
在insert方法中,使用三个参数
第一个参数:必需,指插入的内容,文档数据,是一个JSON对象
第二个参数:配置参数,这里的safe表示,当属性值为true时,使用getLastError命令执行数据的存取操作,该命令返回插入操作的执行结果,默认值为false
第三个参数:回调函数,该回调函数有两个参数,第一个是操作失败时抛出的错误对象,第二个参数是一个JSON对象,表示插入的数据文档,当操作失败时,该参数值为null
注意一下这个返回的数据文档JSON对象的内容格式:
{
result : {ok : 1, n : 1},
ops : [{
name : 'kong',
age : 18,
sex : 'man'
}],
insertedCount : 1,
insertedIds : [570e01ee517dfc7c1d80e51a]
}
所以,如果需要插入数据的name值,则应该通过result.ops[0].name获取