nodeJS連接mongodb

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ù)庫操作

//引入操作類
var mongoose = require('mongoose');
//設(shè)置數(shù)據(jù)庫連接字符串
var DB_CONN_STR = "mongodb://localhost:27017/note";
//連接到數(shù)據(jù)庫
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ù)庫
// 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ù)庫所有數(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);
  });

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容