In mongoose, you can use the save method to insert a new document into the collection.
Through instantiation, all attributes of a model are defined to the mongoose.Schema () object. Register a model in mongoose through mongoose.model () method.
//引入mongoose模块
const mongoose=require("mongoose");
//定义mongodb地址:user表数据库名
const url='mongodb:localhost/user';
//连接mongodb
mongoose.connect(url,function(err){
if(err){
console.log(连接失败!);
return;
}
});
//定义Schema
const userSchema=new mongoose.Schema({
//字段名:字段类型
id:{type:Number},
name:{type:String},
sex:{type:String}
});
//users是集合名也是表名
mongoose.model('users',userSchema);
const users=mongoose.model('users');
//如果想要插入多条数据就运行多次
var art=new users({
id:1,
name:'张三',
sex:'男'
});
//将文档插入集合中
art.save(function(err){
if(err){
console.log("插入失败");
}
});