var n = new Chat();
n.name = "chat room";
n.save(function(){
//console.log(THE OBJECT ID that I just saved);
});
保存したばかりのオブジェクトのオブジェクト ID を console.log したい。Mongooseでそれを行うにはどうすればよいですか?
これは私のために働いた:
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;
});
データベースに保存しなくても、新しいオブジェクト インスタンスを作成した直後に、Mongoose でオブジェクト ID を取得できます。
私はこのコードを 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));
他の回答では、コールバックの追加について言及されていますが、私は .then() を使用することを好みます
n.name = "chat room";
n.save()
.then(chatRoom => console.log(chatRoom._id));
ドキュメントの例:.
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");
});
あなた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;
// ...
});