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.
_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.
insert() In MongoDB, the insert() method inserts a document or documents into the collection. It takes two parameters, the first parameter is the document or array of the document that we want to insert and the remaining are optional. Using this method you can also create a collection by inserting documents.
Mongoose | findById() Function The findById() function is used to find a single document by its _id field. The _id field is cast based on the Schema before sending the command.
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.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With