web-dev-qa-db-ja.com

mongooseを使用してmongodbにドキュメントを挿入し、生成されたIDを取得する方法は?

私はmongooseを使用してmongodbを操作しています。ここで、テストのために、ネイティブ接続によってmongodbにデータを挿入します。

しかし、質問は挿入後に生成されたIDを取得する方法ですか?

私は試した:

var mongoose = require('mongoose');

mongoose.connect('mongo://localhost/shuzu_test');

var conn = mongoose.connection;

var user = {
    a: 'abc'
};

conn.collection('aaa').insert(user);

console.log('User:');
console.log(user);

しかし、それは印刷されます:

{ a: 'abc' }

_idフィールドはありません。

30
Freewind

_idを自分で生成し、データベースに送信できます。

var ObjectID = require('mongodb').ObjectID;

var user = {
  a: 'abc',
  _id: new ObjectID()
};

conn.collection('aaa').insert(user);

これは、MongoDBのお気に入りの機能の1つです。相互にリンクされた多数のオブジェクトを作成する必要がある場合、appとdbの間で何度も往復する必要はありません。アプリですべてのIDを生成してから、すべてを挿入できます。

40

.saveを使用すると、コールバック関数で_idが返されます。

var user = new User({
  a: 'abc'
});

user.save(function (err, results) {
  console.log(results._id);
});
7
martinedwards

Promisesを使用したい場合:

const collection = conn.collection('aaa');
const instance = new collection({ a: 'abc' });
instance.save()
    .then(result => {
        console.log(result.id);  // this will be the new created ObjectId
    })
    .catch(...)

または、Node.js> = 7.6.0を使用している場合:

const collection = conn.collection('aaa');
const instance = new collection({ a: 'abc' });
try {
    const result = await instance.save();
    console.log(result.id);  // this will be the new created ObjectId
} catch(...)
2
Kleber

Upsert:trueオプションでUpdateメソッドを使用できます

aaa.update({
    a : 'abc'
}, {
    a : 'abc'
}, {
    upsert: true
});
1
Rifaideen