I am currently developing a web app using Express, Mongoose, and Angular 2 (TypeScript). I want to post an instance of MyClass
without including the _id
field.
In mongoose, the _id
field is used for various operations in MongoDB. Here is how I have implemented it on the server side using mongoose
:
router.post('/', function(req, res, next) {
Package.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /package/id */
router.get('/:id', function(req, res, next) {
Package.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /package/:id */
router.put('/:id', function(req, res, next) {
Package.findByIdAndUpdate(req.params.id, req.body, function (err, post, after) {
if (err) return next(err);
res.json(post);
});
});
To exclude the _id
field, I have created a TypeScript Class like this:
export class Package{
constructor(
public guid: string,
...
[other fields]
...
public _id: string
){}
}
Please note that the _id
field is included at the end.
In my Angular 2 service, I am posting the JSON object to the server using the following method:
//create new package
private post(pck: Package): Promise<Package> {
let headers = new Headers({
'Content-Type': 'application/json'
});
return this.http
.post(this.packageUrl, JSON.stringify(pck), { headers: headers })
.toPromise()
.then(res => res.json())
.catch(this.handleError);
}
However, I encountered an error as shown in the screenshot below:
https://i.sstatic.net/r6Mp3.png
The error indicated that the object I posted back had an empty _id
field.
How can I post a ts class without including the _id
field, or should I approach this problem differently?