鉴于我所尝试的失败,你如何在MongoDB中存储日期时间?

时间:2017-11-15 15:58:00

标签: javascript mongodb mongoose

我正在尝试在MongoDB中插入日期时间,但我不能。

以下是我使用的方法:

var mongoose = require('mongoose');

var testSchema = new mongoose.Schema({

    date : {
       type : Date 
          }
});

module.exports = mongoose.model('test', testSchema);

2 个答案:

答案 0 :(得分:0)

try { 
    Mongo mongo = new Mongo("yourhost", 27017);
    DB db = mongo.getDB("yourdb");

    DBCollection collection = db.getCollection("yourColl");                  
    DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = (Date)formatter.parse("2-Jun-2012")
    BasicDBObject time = new BasicDBObject("ts", date);
    collection.save(time);
} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (MongoException e) {
    e.printStackTrace();
}

答案 1 :(得分:0)

//您只需在架构中添加默认值:Data.now 。它将100%工作

var mongoose = require('mongoose');

var testSchema = new mongoose.Schema({

    date : {
       type : Date,
       default : Data.now
          }
});

module.exports = mongoose.model('test', testSchema);