Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

node.js - How can I generate an ObjectId with mongoose?

I'd like to generate a MongoDB ObjectId with Mongoose. Is there a way to access the ObjectId constructor from Mongoose?

  • This question is about generating a new ObjectId from scratch. The generated ID is a brand new universally unique ID.

  • Another question asks about creating an ObjectId from an existing string representation. In this case, you already have a string representation of an ID—it may or may not be universally unique—and you are parsing it into an ObjectId.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can find the ObjectId constructor on require('mongoose').Types. Here is an example:

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();

id is a newly generated ObjectId.


Note: As Joshua Sherman points out, with Mongoose 6 you must prefix the call with new:

var id = new mongoose.Types.ObjectId();

You can read more about the Types object at Mongoose#Types documentation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...