NodeJS中使用MongoDB驱动如何将字段设为数据库当前时间?
解决NodeJS MongoDB驱动updateMany设置数据库服务器时间的问题
直接用MongoDB的$currentDate操作符就能实现需求,它会使用数据库服务器的当前时间,完美替代你尝试的$$NOW,而且完全支持updateMany方法。
示例代码:
假设你要更新符合条件的文档,把updatedAt字段设为数据库当前时间:
const { MongoClient } = require('mongodb'); async function updateDocuments() { const client = new MongoClient('your-mongodb-uri'); try { await client.connect(); const db = client.db('your-db-name'); const collection = db.collection('your-collection-name'); // 使用$currentDate设置数据库服务器时间 const result = await collection.updateMany( { /* 你的查询条件 */ }, { $currentDate: { updatedAt: true // true表示设置为当前ISODate格式 // 如果需要毫秒级时间戳,改成: updatedAt: { $type: "timestamp" } } } ); console.log(`更新了${result.modifiedCount}条文档`); } finally { await client.close(); } } updateDocuments();
关键说明:
$currentDate是MongoDB原生操作符,执行时直接在数据库端获取当前时间,完全不受NodeJS服务器时间的影响。- 如果需要的是毫秒级时间戳而非ISODate对象,把配置改成
updatedAt: { $type: "timestamp" }即可。 - 你之前尝试的
$$NOW是MongoDB聚合管道专属变量,普通更新操作(非管道模式)下不生效;而$currentDate是专门为更新场景设计的时间操作符,对updateMany、updateOne等所有更新方法都适用。
内容的提问来源于stack exchange,提问作者Ofek Poliker
相关产品推荐
相关产品推荐

