Node.js mongodb日期插入类似于使用mongoose
我正在mongodb中插入批量记录。我使用本机DB驱动程序来实现这一点,因为性能要高得多。在我的应用程序的其他地方,我使用的是mongoose。我遇到的问题是,mongoose将日期转换为另一种格式,而mongodb native只是将其作为自1970年以来的秒数插入。因此,以后在mongoose中基于该日期的查询不起作用 这是我的猫鼬模式:Node.js mongodb日期插入类似于使用mongoose,node.js,mongodb,express,Node.js,Mongodb,Express,我正在mongodb中插入批量记录。我使用本机DB驱动程序来实现这一点,因为性能要高得多。在我的应用程序的其他地方,我使用的是mongoose。我遇到的问题是,mongoose将日期转换为另一种格式,而mongodb native只是将其作为自1970年以来的秒数插入。因此,以后在mongoose中基于该日期的查询不起作用 这是我的猫鼬模式: var MySchema = new Schema({ name : { type: String, required: t
var MySchema = new Schema({
name : { type: String, required: true },
updatedAt : Date
});
和我的mongo db质量插入:
var newRec = {
name : entry.Name,
updatedAt : Date.now
};
newRecords.push(newRec);
MySchema.collection.insert(newRecords, function(err, newRecs) {
res.json(newRecs.ops);
});
这将在数据库中生成:
{
"_id": {
"$oid": "562818ecf24d540f0053a38d"
},
"name": "Cool Record",
"updatedAt": 12312423512
}
然而,如果通过猫鼬运行,则会产生:
{
"_id": {
"$oid": "561fd90285b5e73f5626f74e"
},
"name": "Cool Record",
"updatedAt": {
"$date": "2015-10-20T20:01:17.553Z"
}
}
如果使用mongoose,这样的查询很有效:
MySchemda.find({ updatedAt : { $gt: lastSynced }}).exec();
但不要使用其他方法。日期。现在的是一个数字,表示自1970年以来的毫秒数。虽然它在概念上表示一个日期,但实际上并不是一个日期:
var x = Date.now;
typeof x;
// "number"
您需要将架构切换为:
var MySchema = new Schema({
name : { type: String, required: true },
updatedAt : Number
});
或者,您可以使用:
var newRec = {
name: entry.Name,
updatedAt: new Date()
}
并保持您的模式不变。您可以这样使用它:
定义日期类型和默认值,然后创建一个变量,该变量可以定义为您的模式使用year:new date
这将有助于设置日期
var songSchema = new mongoose.Schema({
name : String,
year : {type : Date, default : Date.now},
singer : String,
});
var song = mongoose.model("song", songSchema);
var xyz= new song({
name : "abcd",
year :new Date, // to set the date first set new Date
singer : "aabbccdd",
});
您可以使用setDate、setMonth、setYear方法来解决问题。在对象年份下定义了更多方法。您可以在mongoose的文档中进一步了解
xyz.save(function(err, songs){
if(err)
winston.log("Something is wrong"+ " "+ err);
else {
songs.year.setDate(03);
songs.year.setMonth(03);
songs.year.setYear(2015);
winston.log(songs);
}
});