1

Is there a save operation in mongoose.js or mongodb api, which returns the _id of stored entry?

In mongoose the following will save the Entry.

p.save(function (err) {
  if (err) return handleError(err);
  else console.log('saved');
  })
})

Likewise db.collection.save(document) will save document in mongodb api. But in both cases, you need to query db again for _id, which I want to avoid. As it seems ineffient.

4

1 回答 1

0

当您在 Mongoose 中实例化一个对象时,该对象将具有一个_id已分配的对象(默认情况下已在客户端分配)。

所以,如果你只是检查:

console.log(p.id);

在调用 之前,您会看到它有一个值save

并且在使用 Node.JS 的本机驱动程序的情况下,文档在result参数中返回,并带有_id集合。

var collection = db.collection("tests");
collection.insert(p, function(err, results) {
   if (err) { return; }
   // results in an array, and in this case
   // results[0]._id would be available
});
于 2013-11-07T21:34:41.233 回答