使用MongoDB的节点API插入文档的正确方法是什么?

时间:2015-04-22 04:34:30

标签: node.js mongodb

我使用node-mongo查询并将文档插入mongoDB数据库。

这就是我假设插入的内容:

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

});

然而对于insertedDocuments我希望它们是实际文档,但这就是insertedDocuments总是看起来像:

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

解释我所做的重要代码是:

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);
    }
  });
}

奇怪的是,createdPlace的日志如下所示:

{ 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 } ] }

我做错了什么?

1 个答案:

答案 0 :(得分:1)

新记录位于createdPlace.ops[0]。您调用的内容createdPlace不是新文档,而是API文档调用result的包装器对象。它包含有关操作的元数据,然后在ops属性数组下,您可以找到新文档。

以下是the documentation

的摘录
  

insert命令将返回一个结果对象,其中包含可能有用的几个字段。

  • result包含MongoDB的结果文档
  • ops包含使用添加的 _id 字段
  • 插入的文档
  • connection包含用于执行插入的连接

您可能会考虑使用更方便的模块,例如monk,它会将文档返回给您。 (也推荐使用,因为通常mongodb原生API非常糟糕,实际上是开发人员的恶意)。