gpt4 book ai didi

node.js - MongoDB 集合插入添加 _id 字段

转载 作者:太空宇宙 更新时间:2023-11-03 23:04:46 25 4
gpt4 key购买 nike

用于连接到数据库、创建集合和编写文档的简单代码。但是,为什么调用collection.insert会改变jsonobj呢?

var mongo = require('mongodb').MongoClient;

mongo.connect('mongodb://localhost:27017/testDB', function(err, connection) {
if (!err) {
connection.createCollection('test', function (err, collection) {
if (!err) {
var jsonobj = {foo: 'bar', abc: 'xyz'};
collection.insert(jsonobj, function (err, result) {
if (!err) {
//is not equal to the previous value of jsonobj
console.log(jsonobj);
}
});
}
});
}
});

我得到的输出是{ foo: 'bar', abc: 'xyz', _id: 5769a38cd01e25512a3dbdd8 },它不等于jsonobj的原始值。我知道 MongoDB 文档都有一个 _id 字段,但为什么它会添加到我的对象中?

最佳答案

来自:https://docs.mongodb.com/manual/reference/glossary/

_id

A field required in every MongoDB document. The _id field must have a unique value. You can think of the _id field as the document’s primary key. If you create a new document without an _id field, MongoDB automatically creates the field and assigns a unique BSON ObjectId.

您的对象是文档,因此 Mongo 添加它。

关于node.js - MongoDB 集合插入添加 _id 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37954089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com