const userSchema = new mongoose.Schema({ // 说明集合中要存储的字段,字段类型
name: String,
age: Number
});
let User = mongoose.model('User', userSchema);
方法一:创建对象,通过模型创建对象(文档),调用文档的save方法保存到数据库中
let u = new User({name: 'Ge', age: 13});
// 保存文档
u.save((err, product)=>{
if (!err) { // 保存文档成功
console.log('保存文档成功', product)
}
})
方法二:利用模型的create方法增加文档。
User.create({name:'gege', age: 666}, (err,result)=>{ // 返回错误信息,和结果
if (!err){
console.log("插入成功", result);
}
})
User.create([
{name:'gege', age: 666},
{name:'cc', age: 18},
{name:'ww', age: 20},
], (err,result)=>{ // 返回错误信息,和结果
if (!err){
console.log("插入成功", result);
}
})
(async ()=>{
let result = await User.create([
{name:'gege', age: 666},
{name:'cc', age: 18},
{name:'ww', age: 20},
])
console.log(result);
})();
使用find方法 接收三个参数:过滤条件,返回结果的投影条件,回调函数(回调函数接收err,查询到的文档)
User.find({}, {}, (err, docs)=>{
if (!err) {
console.log(docs);
}
})
User.find({}, {_id:0, name: 1, age: 1}, (err, docs)=>{
if (!err) {
console.log(docs);
}
})
User.find({name: 'gege'}, {_id:0, name: 1, age: 1}, (err, docs)=>{
if (!err) {
console.log(docs);
}
})
User.find({}, {_id:0, name: 1, age: 1}, {skip:0, limit:5}, (err, docs)=>{
if (!err) {
console.log(docs);
}
})
(async ()=>{
let resultFind = await User.find({}, {_id:0, name: 1, age: 1}, {skip:0, limit:5})
console.log(resultFind, 'return');
})();
使用update方法 接收三个参数:更新条件,更新后的内容,额外配置)
User.update({name:'gege'}, {$set: {age: 999}}, (err,docs)=>{
if (!err){
console.log("更新成功");
}
})
User.update({name:'gege'}, {$set: {age: 999}}, {multi:true}, (err,docs)=>{
if (!err){
console.log("更新成功");
}
})
(async ()=>{
let resultSearch = await User.update({name:'cc'}, {$set: {age: 999}}, {multi:true});
console.log(resultSearch)
})();
-1 使用remove方法 接收两个参数:删除条件,额外配置)
User.remove({name: 'gege'}, {}, (err, docs)=>{
if(!err){
console.log(err,'删除成功');
}
})
User.deleteOne({name: 'Ge'}, {justOne:true}, (err, docs)=>{
if(!err){
console.log(err,'删除成功');
}
})
(async ()=>{
let resultDelete = await User.deleteOne({name: 'cc'});
})();