mongodb - node.js使用mongoose,static方法如何自动添加时间?

查看:100
本文介绍了mongodb - node.js使用mongoose,static方法如何自动添加时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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等价。

解决方案

假如是自动添加时间,为什么不用:

crawlAt: { type: Date, default: Date.now }


依据您的想法,写了一个statics(使用到async/await)的使用栗子。请主要参考语法,希望有用:

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))

供参考。

Love MongoDB! Have Fun!

这篇关于mongodb - node.js使用mongoose,static方法如何自动添加时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆