I am currently struggling with NestJS in combination with Mongoose.
When I am trying to make a POST request on my nest REST API I get a successful response with all fields I provided. However, I need the _id property in my frontend as well (for navigation purposes).
So the current stored procedure looks like this:
@Injectable()
export class JourneysService {
constructor(@InjectModel(Journey.name) private journeyModel: Model<JourneyDocument>) {}
async create(createJourneyDto: CreateJourneyDto): Promise<Journey> {
const createdJourney = new this.journeyModel(createJourneyDto);
console.log(createdJourney._id);
return await createdJourney.save();
}
[...]
}
The result of console.log(_id) is null.
The object I get back on a POST request is:
return: {
photos: [],
active: true,
_id: null,
createdAt: 2021-01-25T20:36:54.809Z,
updatedAt: 2021-01-25T20:36:54.809Z,
startDate: null,
endDate: null,
title: 'Sample title',
description: 'lorem ipsum dolor sit amet',
__v: 0
}
Notice the _id field containing null.
In the database however the _id field is set as expected.
When I perform a GET request afterwards the _id is also being transmitted:
{
"photos": [],
"active": true,
"_id": "600f2be62ef43be2855e358f",
"createdAt": "2021-01-25T20:36:54.809Z",
"updatedAt": "2021-01-25T20:36:54.809Z",
"startDate": null,
"endDate": null,
"title": "Sample title",
"description": "lorem ipsum dolor sit amet",
"__v": 0
}
So why not on object creation? Does someone know whats wrong? Why is the id field on creation always null?
I have also looked up this question, stating exactly the way I am currently trying to retrieve the _id:
Mongoose with mongodb how to return just saved object?
question from:
https://stackoverflow.com/questions/65892189/nestjs-mongoose-mongodb-object-creation-does-not-provide-id