使用expressjs

时间:2017-03-20 18:29:25

标签: mongodb angular express post mongoose-schema

我有一个MEAN堆栈应用程序,我按照教程构建,我有一个字符串成功保存到数据库,当我尝试使用一次调用实现将多个字符串保存到数据库时我没有错误但是当我尝试检索信息或在mongo shell中查看它有一个元素添加了一个对象ID,但字符串是空白的?我用过console.log();跟着他一直盯着帖子,他们看起来是正确的。

猫鼬模型:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var muv = require('mongoose-unique-validator');

var schema = new Schema({
    firstName: {type: String, required: true},
    lastName: {type: String, required: true},
    empId: {type: String, required: true},
    num: {type: String, required: true},
    job: {type: String, required: true},
});

schema.plugin(muv);

module.exports = mongoose.model('Message', schema);

发布和获取服务:

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

import { Message } from "./message.model";

@Injectable()
export class MessageService {
    constructor(private http: Http) {}

    getMessages(): Observable<any> {
        return this.http.get('http://localhost:3000/messages')
            .map( (data: Response) => {
                const extracted = data.json();
                const msgArray: Message[] = [];
                let message;
                for (let element of extracted.data) {
                    console.log(element.content);
                    message = new Message(element.content, element.content, element.content, element.content ,element.content);
                    msgArray.push(message);
                }
                return msgArray;
            });
    }

    saveMessage(message: Message): Observable<any> {
        console.log(message);
        const body = JSON.stringify(message);
        console.log(body);
        const headers = new Headers({'Content-Type': 'application/json'});
        return this.http.post('http://localhost:3000/message', body, {headers: headers});
    }
}

使用该服务的组件:

import { Component } from '@angular/core';
import { Message } from "./message.model";
import { MessageService } from "./message.service";

@Component({
  moduleId: module.id,
  selector: 'Employees',
  templateUrl: 'employees.component.html',
  providers: [MessageService]
})

export class EmployeesComponent { 

    messages: Message[] = [];

    constructor(private messageService: MessageService) {}

    onAddMessage() {
        const message = new Message('Jim','Smith','EP100','08710101010','Manager');
        this.messages.push(message);
        this.messageService.saveMessage(message)
            .subscribe(
                () => console.log('Success!'),
                error => console.error(error)
            );
    }
}

POST:

router.post('/message', function(req, res, next) {
    console.log(req.body.firstName);
    console.log(req.body.lastName);
    console.log(req.body.empId);
    console.log(req.body.num);
    console.log(req.body.job);

    var message = new Message({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        empId: req.body.empId,
        num: req.body.num,
        job: req.body.job
    });
    message.save(function(err, result) {
        if (err) {
            return res.status(500).json({
                message: 'Error while saving data!'
            });
        }
        res.status(201).json({
            message: 'Saved data successfully'
        });
    });
});

我的mongodb记录,内容是第一个字符串,最后5个未定义的行是我尝试发布上面的模型时:

> db.messages.find().sort({_id:1});
{ "_id" : ObjectId("58c4436e02895f0e0404193d"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c4437102895f0e0404193e"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c4437202895f0e0404193f"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c4461f02895f0e04041940"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c4463302895f0e04041941"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c4463502895f0e04041942"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c4463b02895f0e04041943"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c4465802895f0e04041944"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c4467202895f0e04041945"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c4467c02895f0e04041946"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c45a7569709943d04cb033"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c4600e9674323310888acd"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c463d1baaac10b60663601"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c463d2baaac10b60663602"), "content" : " It worked!", "__v" : 0 }
{ "_id" : ObjectId("58c477780947a84580a2e0b0"), "content" : " It still worked!", "__v" : 0 }
{ "_id" : ObjectId("58cfcd1e2f4cf920841d2f9f"), "__v" : 0 }
{ "_id" : ObjectId("58cfcfd42f4cf920841d2fa0"), "__v" : 0 }
{ "_id" : ObjectId("58cfd4527f1f8303783dacf8"), "__v" : 0 }
{ "_id" : ObjectId("58cfd5008c437e31a85b31e8"), "__v" : 0 }
{ "_id" : ObjectId("58cfd582bb3fb53f2cbf51e0"), "__v" : 0 }

0 个答案:

没有答案