在Mongoose中保存对象后如何获取objectID?

时间:2011-07-28 05:21:14

标签: node.js mongodb mongoose

var n = new Chat();
n.name = "chat room";
n.save(function(){
    //console.log(THE OBJECT ID that I just saved);
});

我想在console.log中保存刚刚保存的对象的对象ID。我如何在Mongoose中做到这一点?

9 个答案:

答案 0 :(得分:98)

这对我有用:

var mongoose = require('mongoose'),
      Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/lol', function(err) {
    if (err) { console.log(err) }
});

var ChatSchema = new Schema({
    name: String
});

mongoose.model('Chat', ChatSchema);

var Chat = mongoose.model('Chat');

var n = new Chat();
n.name = "chat room";
n.save(function(err,room) {
   console.log(room.id);
});

$ node test.js
4e3444818cde747f02000001
$

我在使用mongoose 1.7.2并且这很好用,只是再次运行以确定。

答案 1 :(得分:37)

Mongo将完整的文档作为回调对象发送,因此您只需从那里获取它。

例如

n.save(function(err,room){
  var newRoomId = room._id;
  });

答案 2 :(得分:3)

你可以在新模型之后在mongoosejs中找到目标。

我在mongoose 4中使用此代码工作,您可以在其他版本中尝试

var n = new Chat();
var _id = n._id;

n.save((function (_id) {
  return function () {
    console.log(_id);
    // your save callback code in here
  };
})(n._id));

答案 3 :(得分:3)

您可以手动生成_id,然后您不必担心以后将其撤回。

var mongoose = require('mongoose');
var myId = mongoose.Types.ObjectId();

// then set it manually when you create your object

_id: myId

// then use the variable wherever

答案 4 :(得分:2)

其他答案提到添加回调,我更喜欢使用.then()

n.name = "chat room";
n.save()
.then(chatRoom => console.log(chatRoom._id));

the docs中的示例:。

var gnr = new Band({
  name: "Guns N' Roses",
  members: ['Axl', 'Slash']
});

var promise = gnr.save();
assert.ok(promise instanceof Promise);

promise.then(function (doc) {
  assert.equal(doc.name, "Guns N' Roses");
});

答案 5 :(得分:0)

有了save,您所需要做的就是:

n.save((err, room) => {
  if (err) return `Error occurred while saving ${err}`;

  const { _id } = room;
  console.log(`New room id: ${_id}`);

  return room;
});

以防万一有人想知道如何使用create获得相同的结果:

const array = [{ type: 'jelly bean' }, { type: 'snickers' }];

Candy.create(array, (err, candies) => {
  if (err) // ...

  const [jellybean, snickers] = candies;
  const jellybeadId = jellybean._id;
  const snickersId = snickers._id;
  // ...
});

Check out the official doc

答案 6 :(得分:0)

好吧,我有这个:

TryThisSchema.post("save", function(next) {
    console.log(this._id);
});

请注意第一行中的“帖子”。使用我的Mongoose版本,在保存数据后获取_id值没有问题。

答案 7 :(得分:0)

实际上,实例化对象时ID应该已经存在

var n = new Chat();
console.log(n._id) // => 4e7819d26f29f407b0... -> ID is already allocated

在此处查看此答案:https://stackoverflow.com/a/7480248/318380

答案 8 :(得分:0)

根据猫鼬 v5.x 文档:

<块引用>

save() 方法返回一个承诺。如果 save() 成功,则 promise 解析为已保存的文档。

使用它,这样的东西也可以工作:

let id;
    
n.save().then(savedDoc => {
    id = savedDoc.id;
});