首页 文章

如何使用mongoose将文档插入mongodb并获取生成的id?

提问于
浏览
29

我正在使用猫鼬来操作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 字段 .

4 回答

  • 40

    如果你使用.save,那么你将在回调函数中得到_id .

    var user = new User({
      a: 'abc'
    });
    
    user.save(function (err, results) {
      console.log(results._id);
    });
    
  • 1

    如果你喜欢使用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(...)
    
  • 7

    您可以自己生成 _id 并将其发送到数据库 .

    var ObjectID = require('mongodb').ObjectID;
    
    var user = {
      a: 'abc',
      _id: new ObjectID()
    };
    
    conn.collection('aaa').insert(user);
    

    这是我最喜欢的MongoDB功能之一 . 如果您需要创建多个彼此链接的对象,则无需在app和db之间进行多次往返 . 您可以在应用程序中生成所有ID,然后只需插入所有内容 .

  • 1

    您可以将Update方法与upsert:true选项一起使用

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

相关问题