Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

I'm using mongoose to operate mongodb. Now, for testing, I want to insert some data into mongodb by native connection.

But here my main question is how to get the generated id after inserting?

I tried:

var mongoose = require('mongoose');

mongoose.connect('mongo://localhost/shuzu_test');

var conn = mongoose.connection;

var user = {

    a: 'abc'

};

conn.collection('aaa').insert(user);

console.log('User:');

console.log(user);

But it prints:

{ a: 'abc' }

There is no _id field.

1 Answer

0 votes
by (108k points)
edited by

You can simply generate id by yourself by calling ObjectID function and send it to the database. You can also create all ids in the app and then just insert all your documents.

var ObjectID = require('mongodb').ObjectID;

var user = {

  a: 'abc',

  _id: new ObjectID()

};

conn.collection('CollectionName').insert(user);

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers

500 comments

108k users

Browse Categories

...