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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6854431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:25:17  来源:igfitidea点击:

How do I get the objectID after I save an object in Mongoose?

node.jsmongodbmongoose

提问by TIMEX

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

I want to console.log the object id of the object I just saved. How do I do that in Mongoose?

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

回答by Richard Holland

This just worked for me:

这对我有用:

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
$

I'm on mongoose 1.7.2 and this works just fine, just ran it again to be sure.

我在 mongoose 1.7.2 上,这很好用,只需再次运行以确保。

回答by Anathema.Imbued

Mongo sends the complete document as a callbackobject so you can simply get it from there only.

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

for example

例如

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

回答by yue

you can get objectid in mongoosejs after you new some model.

新建一些模型后,您可以在 mongoosejs 中获得 objectid。

i'm using this code work in mongoose 4, you can try it in other version

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

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

or

或者

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

回答by Glenn

You can manually generate the _id then you don't have to worry about pulling it back out later.

您可以手动生成 _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

回答by rotimi-best

With saveall you just need to do is:

有了save你只需要做的一切:

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

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

  return room;
});

Just in case someone is wondering how to get the same result using create:

以防万一有人想知道如何使用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

查看官方文档

回答by Roddy P. Carbonell

Well, I have this:

嗯,我有这个:

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

Notice the "post" in the first line. With my version of Mongoose, I have no trouble getting the _id value after the data is saved.

注意第一行中的“post”。使用我的 Mongoose 版本,我可以在保存数据后轻松获取 _id 值。

回答by Julian Orinyol

Other answers have mentioned adding a callback, I prefer to use .then()

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

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

example from 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");
});