使用Node JS从Ionic 2 / Angular 3更新Mongo DB中的记录时出错

时间:2018-03-10 13:16:45

标签: angularjs node.js mongodb ionic2

我一直在尝试使用MEAN和Ionic 2/3执行CRUD操作。因此,我是新手,这可能看起来很傻。我正在尝试更新我在MongoDB上的记录。但我没有看到它在我的数据库上得到更新,我如何获得数据成功更新的响应。我似乎获得200状态,但记录没有得到更新

这是我的代码:

这是我的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.Promise = global.Promise;
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/user.js'));
app.listen(port);
//server.listen(port);
console.log("App listening on port " + port);

这是我的router.js

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var UserProfile = require('../models/UserProfile.js');
router.get('/User',function(req,res,next){
  UserProfile.find({FullName:req.query.FullName,CI},function(err,data){
      if(err){
        return next(err)
      }
      res.json(data);
  })
})

router.put('/User/:id',function(req,res){
UserProfile.findByIdAndUpdate({_id:req.params.id},{
  FullName:req.body.FullName,
  City:req.body.city
},function(err,data){
    if (err) return next(err);
    else{
      console.log(data);
      res.json(data);
    }

    }) 

})
module.exports = router;

这是我的模型,userprofile.js

var mongoose = require('mongoose'); 
var ProfileSchema = new mongoose.Schema({
    _id:{
        type:String      
    },
    FullName:{
        type:String       
    },
    EmailID:{
        type:String       
    },
    Phone:{
        type:Number       
    },
    Address1:{
        type:String       
    },
    Address2:{
        type:String       
    },
    PinCode:{
        type:Number       
    },
    Gender:{
        type:String       
    },
    ProfilePic:{
        type:String       
    },
    IDproof:{
        type:String       
    },
    UserName:{
        type:String       
    },
    Password:{
        type:String      
    },
    Dob:{
        type:String       
    },
    City:{
        type:String       
    },
    State:{
        type:String      
    },
    HighestEducation:{
        type:String       

 }
})
module.exports = mongoose.model('UserProfile',ProfileSchema,'User');

我有一个名为profile.ts的提供商

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ProfileProvider {
data : any;
remoteUrl : string = "http://234.234.1.2.ap-south-1.compute.amazonaws.com:8000";
localUrl : string = "http://192.168.0.101:8000/User" ;
headers : any;
  constructor(public http: Http,) {

  }
   public getProfile(EmailID){
    return new Promise(resolve => { 
      this.http.get(this.localUrl+'?EmailID='+EmailID)
        .map(res => res.json())
        .subscribe(data => {
          resolve(data);
        });
    });
  }
  public updateProfile(userId,options){
    console.log(">>>>>>",userId,options)
    this.headers = new Headers({'Content-Type': 'application/json'})
    return new Promise(resolve=>{
      this.http.put(this.localUrl+'/'+userId,options,this.headers).subscribe((data:any)=>{
        resolve(data);
      })
    })

  }
}

最后我的页面,个人资料详情。我删除了所有其他不相关的代码。我从nativestorage获取userId(这里没有提到代码)。目前我只是在点击按钮时使用UpdateRecords()方法。

import { Component } from '@angular/core';
import { NavController, NavParams ,Platform} from 'ionic-angular';
import { NativeStorage } from '@ionic-native/native-storage';
import {FormBuilder, FormGroup, Validators, AbstractControl} from '@angular/forms';
import { CustomValidtorsProvider } from '../../providers/custom-validators/custom-validators';
import { ProfileProvider } from '../../providers/profile/profile';
@Component({
  selector: 'personal-details',
  templateUrl: 'personal-details.html',
})
export class PersonalDetailsPage {
  userId : string;
  headers: any; 
  params : any;
  constructor(public navCtrl: NavController, public ProfileDetails :ProfileProvider, public navParams: NavParams, private nativeStorage : NativeStorage, private fb : FormBuilder,
  private platform : Platform ) 
  {
    platform.ready().then(()=>
    {
      this.nativeStorage.getItem("fbLogin").then((data)=>{
        this.userId = data.id;

      }).catch((c)=>{console.log(c);this.userImg = "http://icons.iconseeker.com/png/fullsize/transformers-x-vol-3/heroic-autobots-1.png"});
      this.nativeStorage.getItem("profileData").then((data)=>{         
      this.userId = data.id;
      }).catch((c)=>{console.log(c)})
    })


  }    

  ionViewDidLoad() {


  }

  UpdateRecords()
  {
   this.params = {FullName:"FirstName LastName1",City:"City1"}
    this.ProfileDetails.updateProfile(this.userId,this.params).then(d=>{
      console.log("Update Record Status >",d)
    }).catch((e)=>{console.log("error:>",e)})
  }
  onSubmit(value: string) : void{ 
    if(this.authForm.valid){
      // 
    }
  }

}

在控制台日志中,我得到了这个"更新记录状态>回复 {body:" null",status:200,ok:true,statusText:" ok",headers,..} 我猜它是可能会更新,但当我检查Mongo数据库和我的收藏中它没有反映。请帮帮我。

1 个答案:

答案 0 :(得分:1)

你不应该在你的架构中定义_id,除非你的意图是自己管理id(这可能会令人讨厌)。如果省略模式中的字段定义,Mongoose将自动创建此字段并为您管理。

此外,除非文档已存在于您的收藏中,否则findAndUpdateById(...)无法正常工作。

如果您想要创建记录(如果它不存在),您可以使用UserProfile.findOneAndUpdate(query, objectDataToUpdate, { upsert: true })定义的herequery可以是{ _id: ObjectId('...') }