在MERN(MongoDB, Express.js, React, Node.js)堆栈中,使用Mongoose作为MongoDB的对象建模工具时,可以通过多种方式获取新创建文档的时间戳。以下是一些基础概念和相关操作:
在Mongoose中,你可以在Schema定义中启用timestamps
选项,这样Mongoose会自动为你添加createdAt
和updatedAt
字段。
const mongoose = require('mongoose');
// 定义Schema
const userSchema = new mongoose.Schema({
name: String,
email: String,
// 其他字段...
}, { timestamps: true }); // 启用时间戳
// 创建Model
const User = mongoose.model('User', userSchema);
// 创建新用户
const newUser = new User({
name: 'John Doe',
email: 'john.doe@example.com'
});
newUser.save()
.then(user => {
console.log('User created:', user);
// 输出将包含createdAt和updatedAt字段
})
.catch(err => {
console.error('Error creating user:', err);
});
timestamps
选项。{ timestamps: true }
。通过上述方法,你可以有效地在MERN堆栈中使用Mongoose获取和管理文档的时间戳。如果遇到其他具体问题,可以根据错误信息和日志进一步排查解决。
领取专属 10元无门槛券
手把手带您无忧上云