47

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

But the 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.

Freewind
  • 185,914
  • 150
  • 408
  • 676

4 Answers4

51

You can generate _id yourself and send it to the database.

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

var user = {
  a: 'abc',
  _id: new ObjectID()
};

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

This is one of my favourite features of MongoDB. If you need to create a number of objects, that are linked to each other, you don't need to make numerous round-trips between app and db. You can generate all ids in the app and then just insert everything.

Sergio Tulentsev
  • 219,187
  • 42
  • 361
  • 354
  • Doesn't new ObjectID() need to do a round trip to get an "available" ID?... otherwise, would there not be an extremely small chance of a collision? (( for instance, on MSSQL, NEWID() is compliant with RFC4122... and ensures no collisions, but it occurs on the DB side.)) – George 2.0 Hope Oct 18 '17 at 23:12
  • I did some further research, and came across this SOQuestion [https://stackoverflow.com/a/5694803/1327508] which explains both how the oid is generated & the 3 (+1 in comment) scenarios for collision... & my answer is essentially, "no, you're correct", because of how the oid is generated. – George 2.0 Hope Oct 19 '17 at 03:24
  • seems that IObjectID is depracted , "invalid schema configuration: `_id` schematype definition is invalid" – clay Jan 29 '22 at 17:48
13

If you use .save then you'll get the _id back in the callback function.

const User = require('../models/user.js');    

var user = new User({
  a: 'abc'
});

user.save(function (err, results) {
  console.log(results._id);
});
martinedwards
  • 5,197
  • 1
  • 31
  • 31
4

If you like using Promises:

const collection = conn.collection('aaa');
const instance = new collection({ a: 'abc' });
instance.save()
    .then(result => {
        console.log(result.id);  // this will be the new created ObjectId
    })
    .catch(...)

Or if you're using Node.js >= 7.6.0:

const collection = conn.collection('aaa');
const instance = new collection({ a: 'abc' });
try {
    const result = await instance.save();
    console.log(result.id);  // this will be the new created ObjectId
} catch(...)
Kleber
  • 834
  • 13
  • 24
2

You can use the Update method with upsert: true option

aaa.update({
    a : 'abc'
}, {
    a : 'abc'
}, {
    upsert: true
});
Moh .S
  • 1,704
  • 17
  • 19