nodejs中使用mongoose连接mongodb,如何在static方法中自动添加时间?下面代码添加的时间一直是代码刚开始运行的时间。
import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
const ContentSchema = new Schema({
content: {
type: String
},
status: {
type: Number
},
crawlAt: {
type: Date
}
}, { _id: false });
ContentSchema.statics.uniSave = async (doc,cb) => {
try{
doc.crawlAt = doc.crawlAt ? doc.crawlAt : new Date;
console.log(doc);
await doc.save();
}catch(error){
cb(error);
}}
const Crawl = mongoose.model('Crawl', ContentSchema,'crawl');
let document = new Crawl({content:"This is example",status: 404})
// 直接插入
Crawl.uniSave(document, v => console.log(v))
setTimeout(async function () {
// 延迟插入
await Crawl.uniSave(document, v => console.log(v))
}, 1000 * 10);
打印信息
// 直接插入
{ crawlAt: 2017-03-27T04:58:53.992Z,
content: 'This is example',
status: 404 }
// 延迟插入
{ crawlAt: 2017-03-27T04:58:53.992Z,
content: 'This is example',
status: 404 }
我想要的效果是延迟插入时间大于直接插入时间(例子是在10秒后),实际跑出来的两个时间是相等的。是因为setTimeout()方法的问题吗?
解决:我的问题是每次测试保存其实用的同一个文档,所以时间一直相同。
schema.static('method', cb)和schema.static.method = cb等价。
If the time is added automatically, why not use:
crawlAt: { type: Date, default: Date.now }
Based on your ideas, I wrote a usage example of statics (using async/await). Please mainly refer to the grammar, hope it is useful:
For reference.
Love MongoDB! Have Fun!
I want to learn how to add custom time in static, for example, a more complex time setting method. Defining it in the schema above can only achieve a fixed time point.