如何使用 mongoose 将文档插入 mongodb 并获取生成的 id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10520501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert a doc into mongodb using mongoose and get the generated id?
提问by Freewind
I'm using mongoose to operate mongodb. Now, for testing, I want to inserting some data into mongodb by native connection.
我正在使用 mongoose 来操作 mongodb。现在,为了测试,我想通过本机连接将一些数据插入到 mongodb 中。
But the question is how to get the generated id after inserting?
但问题是插入后如何获取生成的id?
I tried:
我试过:
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);
But it prints:
但它打印:
{ a: 'abc' }
There is no _id
field.
没有_id
字段。
回答by Sergio Tulentsev
You can generate _id
yourself and send it to the database.
您可以_id
自己生成并将其发送到数据库。
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.
这是我最喜欢的 MongoDB 功能之一。如果您需要创建多个相互链接的对象,则无需在 app 和 db 之间进行多次往返。您可以在应用程序中生成所有 ID,然后插入所有内容。
回答by martinedwards
If you use .save then you'll get the _id back in the callback function.
如果您使用 .save ,那么您将在回调函数中获得 _id 。
var user = new User({
a: 'abc'
});
user.save(function (err, results) {
console.log(results._id);
});
回答by Kleber
If you like using Promises:
如果你喜欢使用 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:
或者,如果您使用的是 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(...)
回答by Moh .S
You can use the Update method with upsert: true option
您可以使用带有 upsert: true 选项的 Update 方法
aaa.update({
a : 'abc'
}, {
a : 'abc'
}, {
upsert: true
});