可以使用原生的Node.js操作mongodb数据库的驱动程序来实现不使用mongoose/mongodb填充对象键的功能。以下是一个示例代码:
const MongoClient = require('mongodb').MongoClient;
async function populateObjectKeys() {
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';
const client = new MongoClient(url, { useUnifiedTopology: true });
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('mycollection');
// 查询数据
const data = await collection.findOne({});
// 转换数据
const transformedData = {};
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
transformedData[key] = data[key];
}
}
console.log(transformedData);
} catch (err) {
console.error(err);
} finally {
client.close();
}
}
populateObjectKeys();
上述代码中,我们使用了mongodb
模块提供的MongoClient
来连接并操作数据库。首先,我们通过await client.connect()
连接到数据库。然后,我们通过db.collection('mycollection')
获取到要操作的集合(mycollection
)。接下来,我们使用findOne({})
方法查询集合中的一条数据。然后,我们使用一个循环遍历数据对象的所有键,并将其赋值给一个新的对象transformedData
中。最后,我们打印出transformedData
。
请注意,上述代码中的连接URL和数据库名称需要根据实际情况进行修改。