49

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
  • 193,756
  • 157
  • 432
  • 708

5 Answers5

52

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
  • 226,338
  • 43
  • 373
  • 367
  • 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
16

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,577
  • 1
  • 33
  • 35
5

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
  • 942
  • 1
  • 15
  • 25
2

You can use the Update method with upsert: true option

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

const User = require('./userModel.js');

const InsertUser = async (req, res) => { // Obtain the user object from req.body (assuming you have bodyParser or similar middleware configured) const userObject = req.body;

try {
    await User.create(userObject);
    res.status(200).json({ message: 'User inserted successfully' });
} catch (error) {
    res.status(500).json({ error: 'Failed to insert user' });
}

};