Подтвердить что ты не робот

Как получить объектID после сохранения объекта в Mongoose?

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

Я хочу console.log идентификатор объекта только что сохраненного объекта. Как это сделать в Mongoose?

4b9b3361

Ответ 1

Это просто сработало для меня:

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, и это работает просто отлично, просто побежал за ним, чтобы быть уверенным.

Ответ 2

Mongo отправляет полный документ как callbackobject, поэтому вы можете просто получить его только оттуда.

например

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

Ответ 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));

Ответ 4

Вы можете вручную сгенерировать _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

Ответ 5

С 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;
  // ...
});

Проверьте официальный документ