반응형
Mongoose에서 객체를 저장 한 후 어떻게 objectID를 얻습니까?
var n = new Chat();
n.name = "chat room";
n.save(function(){
//console.log(THE OBJECT ID that I just saved);
});
방금 저장 한 개체의 개체 ID를 console.log하고 싶습니다. 몽구스에서 어떻게하나요?
이것은 나를 위해 일했습니다.
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를 사용하고 있으며 이것은 잘 작동하며 확인하기 위해 다시 실행했습니다.
Mongo는 전체 문서를 콜백 객체로 전송하므로 여기에서만 가져올 수 있습니다.
예를 들면
n.save(function(err,room){
var newRoomId = room._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
일부 모델을 새로 만든 후에 mongoosejs에서 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));
다음과 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;
// ...
});
글쎄요,이게 있어요
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.
반응형
'Nice programing' 카테고리의 다른 글
| 전체 문자열을 정규식과 어떻게 일치 시키나요? (0) | 2020.11.10 |
|---|---|
| 스프링 보안으로 사용자를 수동으로 로그 아웃하는 방법은 무엇입니까? (0) | 2020.11.10 |
| 활성 예외없이 호출 된 C ++ 종료 (0) | 2020.11.10 |
| 데이터베이스에서 문자열 일부 검색 및 바꾸기 (0) | 2020.11.09 |
| MySQL Workbench에서 테이블 생성 스크립트를 얻는 방법은 무엇입니까? (0) | 2020.11.09 |