如何使用Node js和Ionic 2基于特定字段从mongo db中获取

时间:2018-02-15 17:06:10

标签: node.js mongodb ionic2

我正在使用Node JS和MongoDb以及Ionic 2.我正在尝试根据emailID检索用户的详细信息,我想传递所需的emailID并获取详细信息

这是我的Server.js

// set up ======================================================================
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
var server = require('http').Server(app);
var mongoose = require('mongoose');                 // mongoose for mongodb
var port = process.env.PORT || 8000;                // set the port
var database = require('./config/database');            // load the database config
var morgan = require('morgan');
var methodOverride = require('method-override');
var io = require('socket.io')(server);
var cors = require('cors');
var messageId = {};

// configuration ===============================================================
// Connect to DB
mongoose.connect(database.remoteUrl)
mongoose.connection.on('error', function(e) {
    console.log('Can not connect Error:>>',e);
    process.exit();
});
mongoose.connection.once('open', function(d) { 
    console.log("Successfully connected to the database");
})
//app.use(express.static('./public'));      // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(cors());
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
 });

io.set('origins', '*:*');
http = require('http'),
server = http.createServer(function (req, res) {
    //res.writeHead(200,{'content-type':'text/plain'});
    //  res.write("Sever On");
    // res.end();
}),
io = io.listen(server);
io.on('connection', function (socket) {
    console.log('User Connected -- Server Online');   
    socket.on('message', function (msg,msgId) {
        io.emit('message', "Hello");
        console.log("message from client:", msg);
         setInterval(function(){
          io.emit("messageStatus",msgId);
      },500)
   });
});

app.use(require('./app/routes.js'));
app.listen(port);
//server.listen(port);
console.log("App listening on port " + port);

我目前正在localhost:8000

上运行服务器

这是我的config / database.js,我使用AWS来托管我的MongoDB

module.exports = {
    remoteUrl : 'mongodb://username:password@ec2-22-127-21-183.ap-south-1.compute.amazonaws.com:27017/testdb'

};

我已经基于MongoDB创建了一个Schema,将其命名为userprofile.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProfileSchema = new Schema({
    id:{
        type:String,
        required:true
    },
    FirstName:{
        type:String,
        required:true
    },
    LastName:{
        type:String,
        required:true
    },
    EmailID:{
        type:String,
        required:true
    },
    Phone:{
        type:Number,
        required:true
    },
    Address1:{
        type:String,
        required:true
    },
    Address2:{
        type:String,
        required:true
    },
    PinCode:{
        type:Number,
        required:true
    },
    Gender:{
        type:String,
        required:true
    },
    ProfilePic:{
        type:String,
        required:true
    },
    IDproof:{
        type:String,
        required:true
    },
    UserName:{
        type:String,
        required:true
    },
    Password:{
        type:String,
        required:true
    },
    Dob:{
        type:Number,
        required:true
    },
    City:{
        type:String,
        required:true
    },
    State:{
        type:String,
        required:true
    },
    HighestEducation:{
        type:String,
        required:true
    }
})
module.exports = mongoose.model('UserProfile',ProfileSchema,'User');

这是我的route.js

var express = require('express')
var app = module.exports = express.Router();
var UserProfile = require('./models/UserProfile');


app.get('/User', function (req, res) {
    UserProfile.find(function (err, profile) {
        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
           return res.json({"success":false,"msg":err})
           console.log(err);
        }
        res.status(200).send({"success":true,"result":profile}) 
   });
});

在Ionic 2中,我创建了一个名为Profile.ts的提供者

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Config } from 'ionic-angular/config/config';
import { Response } from '@angular/http/src/static_response';    

 const CONFIG = {apiUrl:'mongodb://username:password@ec2-12-217-232-182.ap-south-1.compute.amazonaws.com:27017/testdb'}
@Injectable()
export class ProfileProvider {

  constructor(public http: Http,) {

  }

  public getProfile(){
    return this.http.get(CONFIG.apiUrl+'User').map(response => response.json().result);
  }

}

这是我的Ionic页面,为了演示而假设我在一个名为 userEmail 的变量中有一个硬编码的电子邮件ID。我如何将它传递给Node JS,然后传递给Mongo DB以获取详细信息。

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams,Platform, Navbar} from 'ionic-angular';
import { ToastController } from 'ionic-angular';
import { NativeStorage } from '@ionic-native/native-storage';
import { TutorPage } from '../tutor/tutor';
import { StudentPage } from '../student/student';
import { Observable } from 'rxjs/Observable';
import { ProfileProvider } from '../../providers/profile/profile';
@Component({
selector: 'page-profile',
templateUrl: 'profile.html'
})
export class ProfilePage {
userImg : any;
userName : string;
profileType :string;
instr : boolean;
stud :boolean;
userEmail : string = "abc@gmail.com";
lastSeen : any;
selectedProfile : any;
canLeavePage : boolean = false;
User: Observable<any>;
@ViewChild('navbar') navBar: Navbar;
  constructor(public navCtrl: NavController, private nativeStorage : NativeStorage, private toastCtrl : ToastController, platform : Platform,
  public ProfileDetails : ProfileProvider) {
  }

  fetchProfileDetails(){
    this.User = this.ProfileDetails.getProfile();
    console.log(this.User)
  }

}

在Mongo DB中,我有一个名为testdb的数据库 我有一个名为User的集合 这是表格中的一个条目的样本

db.User.find().pretty()
{
        "_id" : ObjectId("5a83d1400d47870303228bfa"),
        "FirstName" : "Jazz",
        "LastName" : "Ben",
        "EmailID" : "abc@gmail.com",
        "Phone" : 7654329878,
        "Address1" : "Golden Tulip Est",
        "Address2" : "Earth",
        "PinCode" : 500084,
        "Gender" : "WhoCares",
        "ProfilePic" : "hugyft.in",
        "IDproof" : "hugyc.in",
        "UserName" : "Jazz",
        "Password" : "1736127",
        "Dob" : 1071985,
        "City" : "TheBest",
        "State" : "Solid",
        "HighestEducation" : "PHD"
}

请帮我理解我哪里出错了。

1 个答案:

答案 0 :(得分:1)

您没有传递MongoDB查询的搜索条件。 UserProfile.find(查询,回调)

   app.get('/User', function (req, res) {
        UserProfile.find({
            EmailID: req.query.EmailID
        }, function (err, profile) {
            // if there is an error retrieving, send the error. nothing after res.send(err) will execute
            if (err) {
                return res.json({
                    "success": false,
                    "msg": err
                })
                console.log(err);
            }
            res.status(200).send({
                "success": true,
                "result": profile
            })
        });
    });

Angular Http Call你没有传递任何emailId。

return this.http.get(CONFIG.apiUrl+'User?EmailID=abc@abc.com').map(response => response.json().result);