我一直在尝试使用 MEAN 和 Ionic 2/3 执行 CRUD 操作。我是新手,因此,这可能看起来很愚蠢。我正在尝试更新我在MongoDB上的记录。但是我没有看到它在我的数据库上更新,我如何获得数据已成功更新的响应。我似乎获得了 200 的状态,但记录没有更新
这是我的代码:
这是我的服务器.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);
这是我的路由器.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;
这是我的模型,用户配置文件.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);
})
})
}
}
最后是我的页面,个人资料详细信息.ts我已经删除了所有其他不相关的代码。我从本机存储中获取用户ID(只是此处未提及该代码)。目前,我只是在单击按钮时使用方法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数据库和我的集合时,它没有反映。请帮我解决这个问题。
除非您打算自己管理 ids(这可能会令人讨厌),否则您不应该真正在架构中定义_id
。 如果您从架构中省略字段定义,Mongoose 将自动创建此字段并为您管理它。
此外,除非文档已存在于您的集合中,否则findAndUpdateById(...)
不起作用。
如果要创建不存在的记录,可以使用此处定义的UserProfile.findOneAndUpdate(query, objectDataToUpdate, { upsert: true })
。query
可以{ _id: ObjectId('...') }
的地方.