如何使用mongoose将文档插入mongodb并获取生成的ID? [英] How to insert a doc into mongodb using mongoose and get the generated id?
问题描述
我正在使用猫鼬来操作mongodb.现在,为了进行测试,我想通过本机连接将一些数据插入到mongodb中.
I'm using mongoose to operate mongodb. Now, for testing, I want to inserting some data into mongodb by native connection.
但是问题是插入后如何获取生成的ID?
But the question is how to get the generated id after inserting?
我尝试过:
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
字段.
推荐答案
您可以自己生成_id
并将其发送到数据库.
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);
这是我最喜欢的MongoDB功能之一.如果需要创建彼此链接的许多对象,则无需在app和db之间进行大量往返.您可以在应用中生成所有ID,然后只需插入所有内容即可.
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.
这篇关于如何使用mongoose将文档插入mongodb并获取生成的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!