项目
db.js
var mongoose = require(‘mongoose‘); mongoose.connect(‘mongodb://127.0.0.1:27017/whhhh‘, { useMongoClient: true }); var db = mongoose.connection; db.on(‘error‘, console.error.bind(console, ‘connection error:‘)); db.once(‘open‘, function (callback) { console.log("数据库成功连接"); }); module.exports = db;
try.js
var User = require("./user.js"); /** * 插入 */ function insert() { var user = new User({ username : ‘zhangxiao‘, //用户账号 usersex: ‘nan‘, //密码 userage: 17, //年龄 }); user.save(function (err, res) { if (err) { console.log("Error:" + err); } else { console.log("Res:" + res); } }); } insert();
user.js
/** * Created by ZXW on 2017/11/1. */ var mongoose = require(‘mongoose‘); var db = require("./db.js"); var Schema=mongoose.Schema; var UserSchema = new mongoose.Schema({ username:{type:String}, usersex:{type:String}, userage:{type:Number} }); module.exports = mongoose.model(‘User‘,UserSchema);
运行效果:
结果在robmongo工具中查看
数据库:
2017-11-01 23:56:20
时间: 2024-10-10 23:28:31