diegoaguilar
diegoaguilar

Reputation: 8376

What's proper way to insert a document using node API for MongoDB?

I'm using node-mongo for querying and inserting documents to a mongoDB database.

This is what I'm assuming for inserting:

collection.insert({}, function(err,insertedDocuments){

});

However for insertedDocuments I expect them to be the actual documents, but this is what insertedDocuments is always looking like:

{"ok":1,"n":1}

The important code to explain what I'm doing is:

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

MongoClient.connect('mongodb://127.0.0.1:27017/places', function (err, db) {

  if (err) throw err;
  console.log("Connected to database ... Will work with default places collection".inverse);
  places = db.collection('places');
  strings = db.collection('strings');

  app.route('/places').post(newPlaceController);

  app.listen(6190, function() {
    console.log('Express listening'.inverse);
  });
});

function newPlaceController (request,response) {

  console.log(request.body);
  var latitude = request.body.lat;
  var longitude = request.body.long;
  var name = request.body.name;

  var newPlace = getNewPlaceObject(name,latitude,longitude);  // This returns the object/document to be inserted

  places.insert(newPlace, function (err,createdPlace) {

    if (err)
      response.send(JSON.stringify(err),500);

    else {
      console.log(createdPlace);
      response.send(JSON.stringify(createdPlace),200);
    }
  });
}

Strangely, the log of createdPlace looks like this:

{ result: { ok: 1, n: 1 },
  connection: 
   { domain: null,
     _events: 
      { close: [Object],
        error: [Object],
        timeout: [Object],
        parseError: [Object],
        connect: [Function] },
     _maxListeners: 10,
     options: 
      { socketOptions: {},
        auto_reconnect: true,
        host: '127.0.0.1',
        port: 27017,
        cursorFactory: [Object],
        reconnect: true,
        emitError: true,
        size: 5,
        disconnectHandler: [Object],
        bson: {},
        messageHandler: [Function],
        wireProtocolHandler: {} },
     id: 2,
     logger: { className: 'Connection' },
     bson: {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 27017,
     host: '127.0.0.1',
     keepAlive: true,
     keepAliveInitialDelay: 0,
     noDelay: true,
     connectionTimeout: 0,
     socketTimeout: 0,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     cert: null,
     key: null,
     passphrase: null,
     ssl: false,
     rejectUnauthorized: false,
     responseOptions: { promoteLongs: true },
     flushing: false,
     queue: [],
     connection: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        onend: null,
        destroyed: false,
        bytesRead: 56,
        _bytesDispatched: 215,
        _pendingData: null,
        _pendingEncoding: '',
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        pipe: [Function],
        addListener: [Function: addListener],
        on: [Function: addListener],
        pause: [Function],
        resume: [Function],
        read: [Function],
        _consuming: true },
     writeStream: null,
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null },
  ops: [ { name: 'OXXO', loc: [Object], _id: 553723a2a2c10c273605309a } ] }

What am I doing wrong?

Upvotes: 0

Views: 87

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 145994

The new record is at createdPlace.ops[0]. What you are calling createdPlace is not the new document, but a wrapper object the API docs call result. It contains metadata about the operation and then under the ops property array you can find the new documents.

Here's an excerpt from the documentation

The insert command will return a results object that contains several fields that might be useful.

  • result Contains the result document from MongoDB
  • ops Contains the documents inserted with added _id fields
  • connection Contains the connection used to perform the insert

You might consider a more-convenient module such as monk which will return the document to you. (Also recommended because in general the mongodb native API is so bad it's practically developer-hostile).

Upvotes: 1

Related Questions