44

我正在使用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字段。

4

4 回答 4

50

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

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

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

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

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

于 2012-05-09T16:52:53.823 回答
12

如果您使用 .save ,那么您将在回调函数中取回 _id 。

const User = require('../models/user.js');    

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

user.save(function (err, results) {
  console.log(results._id);
});
于 2017-02-10T18:46:29.973 回答
4

如果你喜欢使用 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(...)
于 2018-04-20T13:11:48.740 回答
2

您可以使用带有 upsert: true 选项的 Update 方法

aaa.update({
    a : 'abc'
}, {
    a : 'abc'
}, {
    upsert: true
});
于 2017-12-20T08:00:00.613 回答