user模型
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var UserSchema = new Schema(
{
name: String,
password: String
});
module.exports = mongoose.model('User', UserSchema);
數(shù)據(jù)庫(kù)操作
//引入操作類
var mongoose = require('mongoose');
//設(shè)置數(shù)據(jù)庫(kù)連接字符串
var DB_CONN_STR = "mongodb://localhost:27017/note";
//連接到數(shù)據(jù)庫(kù)
mongoose.connect(DB_CONN_STR);
//引入 User 模型
var UserModel = require('./models/user');
//創(chuàng)建一個(gè)用戶實(shí)體
var user = new UserModel({
name: "xyz22",
password: "debbie0604"
}
);
//將用戶的實(shí)體插入數(shù)據(jù)庫(kù)
// user.save(function (err, user) {
// if (err)
// throw err;
// console.log(user);
// })
//模型查詢符合條件的數(shù)據(jù) 模糊查詢
UserModel
.find({
name: /xyz/
},{name:1,password:1}, function (err, userArrays) {
if (err)
throw err;
if(userArrays.length>0){
console.log("存在");
console.log(userArrays);
}else{
console.log("不存在");
}
})
//模型查詢數(shù)據(jù)庫(kù)所有數(shù)據(jù) 模糊查詢
UserModel
.find({}, {
name: 1,
password: 1
}, function (err, userArrays) {
if (err)
throw err;
console.log("selectAll");
if (userArrays.length > 0) {
console.log("存在");
console.log(userArrays);
} else {
console.log("不存在");
}
})
//查詢符合條件的記錄數(shù)目
var totalCount=UserModel.count({},function(err,res) {
if(err)
throw err;
console.log("總記錄數(shù)");
console.log(res);
});