Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

node.js - NestJS & Mongoose (MongoDB) - Object creation does not provide _id

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...