How to insert a doc into mongodb using mongoose and get the generated id?

前端 未结 4 1373
渐次进展
渐次进展 2020-12-16 10:06

I\'m using mongoose to operate mongodb. Now, for testing, I want to inserting some data into mongodb by native connection.

But the question is how to get the generat

相关标签:
4条回答
  • 2020-12-16 10:22

    If you like using 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(...)
    

    Or if you're using 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(...)
    
    0 讨论(0)
  • 2020-12-16 10:34

    You can generate _id yourself and send it to the database.

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

    This is one of my favourite features of MongoDB. If you need to create a number of objects, that are linked to each other, you don't need to make numerous round-trips between app and db. You can generate all ids in the app and then just insert everything.

    0 讨论(0)
  • 2020-12-16 10:34

    If you use .save then you'll get the _id back in the callback function.

    var user = new User({
      a: 'abc'
    });
    
    user.save(function (err, results) {
      console.log(results._id);
    });
    
    0 讨论(0)
  • 2020-12-16 10:34

    You can use the Update method with upsert: true option

    aaa.update({
        a : 'abc'
    }, {
        a : 'abc'
    }, {
        upsert: true
    });
    
    0 讨论(0)
提交回复
热议问题