Get _id of an inserted document in MongoDB?

前端 未结 6 1854
渐次进展
渐次进展 2020-12-07 00:34

say I have a product listing. When I add a new product I save it using something like

var doc=products.Insert(p);

The pro

6条回答
  •  -上瘾入骨i
    2020-12-07 00:50

    When you insert an object into the mongodb, mongo will update the object with the internal ID.

    So if

    data = {
      title: "Howdy"
    }
    

    Then when we insert the data object into the db

    db.collection('collectionName', function(err, collection) {
      collection.insert(data);
      console.log(data._id); // <- The mongodb id is now set on the item
    });
    

提交回复
热议问题