Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a doc into mongodb using mongoose and get the generated id?

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.

like image 869
Freewind Avatar asked May 09 '12 16:05

Freewind


People also ask

Does Mongoose auto generate ID?

_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.

Which method is used to insert document in MongoDB?

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.

What does find by id return Mongoose?

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.


2 Answers

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.

like image 145
Sergio Tulentsev Avatar answered Sep 21 '22 14:09

Sergio Tulentsev


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); }); 
like image 43
martinedwards Avatar answered Sep 21 '22 14:09

martinedwards