简体   繁体   中英

Obtain Newly Created Object ID in MongoDB

I have the following MongoDB query and I am using the mongodb node.js driver to connect:

db.collection('employee').insertOne(employeeObj).then(result => {
    console.log(result);
    res.send(result);
}).catch(function (err) {
    console.log("ERROR: ", err);
});

From the above, I would like to obtain the newly created employee's Object _Id but when I console log the result, I get:

Object { n: 1, ok: 1 }

Using the above query, how can I also include the new _id just created within the returned result?

I assume you are using mongoose package. If you want to create custom _id for your document you can use

var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');

and pass it with your employee object.

more info go here .

The result object should contain a insertedId property which is driver generated ObjectId for the insert operation.

Try to log result.insertedId to check the id, and also you should have the inserted object in the ops property.

The _id field would be added to the employeeObj once it is added to the collection.

This is from the docs :

insertOne(doc, options, callback)

Inserts a single document into MongoDB. If documents passed in do not contain the _id field, one will be added to each of the documents missing it by the driver, mutating the document. This behavior can be overridden by setting the forceServerObjectId flag.

Just change the code to:

db.collection('employee').insertOne(employee).then(result => {
    console.log(employee._id);
    res.send({employee, result});
}).catch(function (err) {
    console.log("ERROR: ", err);
});

This might be helpful too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM