복붙노트

[MONGODB] 어떻게 몽구스의 객체 저장 I 후 ObjectId가받을 수 있나요?

MONGODB

어떻게 몽구스의 객체 저장 I 후 ObjectId가받을 수 있나요?

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

나는 방금 저장 한 오브젝트의 오브젝트 ID를 CONSOLE.LOG 싶다. 어떻게 그 몽구스에해야합니까?

해결법

  1. ==============================

    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
    $
    

    나는 몽구스 1.7.2에있어이 작품은 잘 단지 확인하기 위해 다시 달렸다.

  2. ==============================

    2.당신은 단순히 거기에만에서 그것을 얻을 수 있도록 몽고는 callbackobject로 전체 문서를 전송합니다.

    당신은 단순히 거기에만에서 그것을 얻을 수 있도록 몽고는 callbackobject로 전체 문서를 전송합니다.

    예를 들면

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

    3.당신은 수동으로 당신이 나중에 후퇴에 대해 걱정할 필요가 없습니다 다음 _id를 생성 할 수 있습니다.

    당신은 수동으로 당신이 나중에 후퇴에 대해 걱정할 필요가 없습니다 다음 _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. ==============================

    4.당신은 당신이 후 몽구스 JS에서 newsome 모델을 OBJECTID 얻을 수 있습니다.

    당신은 당신이 후 몽구스 JS에서 newsome 모델을 OBJECTID 얻을 수 있습니다.

    내가 몽구스 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));
    
  5. ==============================

    5.당신은 그냥 할 필요가 저장으로 :

    당신은 그냥 할 필요가 저장으로 :

    n.save((err, room) => {
      if (err) return `Error occurred while saving ${err}`;
    
      const { _id } = room;
      console.log(`New room id: ${_id}`);
    
      return room;
    });
    

    이런 경우에 누군가가 만들 사용하여 동일한 결과를 얻을하는 방법을 궁금해 :

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

    공식 문서를 확인하세요

  6. ==============================

    6.글쎄, 난이 있습니다 :

    글쎄, 난이 있습니다 :

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

    첫 번째 줄의 "게시물"에 주목. 몽구스의 내 버전으로, 나는 아무 문제 데이터가 저장 후 _id 값을 얻기가 없습니다.

  7. from https://stackoverflow.com/questions/6854431/how-do-i-get-the-objectid-after-i-save-an-object-in-mongoose by cc-by-sa and MIT license