我目前正在使用带有mongoose的nodejs来更新mongodb文档。但是,我试图将字段从Date类型更改为String类型。我认为这会很简单,但这显然不起作用......
function loopThroughDocs(docs) {
var x = 1;
docs.forEach(function(i) {
//sendNewDate and id for update in db
var dateFormat = formatDate(i.releaseDate);
updateProjWithStringDate(i, dateFormat);
x++;
});
if(x > docs.length) {
console.log("Finished going through docs");
}
}
function formatDate(theDate) {
var dateObj = new Date(theDate);
var month = dateObj.getUTCMonth(); //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var monthsName = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
if(year < 2016) {
console.log("Date is blank _____________");
return "";
} else {
console.log("Date is originally " + theDate);
return monthsName[month] + " " + day + ", " + year;
}
}
function updateProjWithStringDate(proj, stringDate) {
Project.update({_id: proj._id}, {releaseDate: stringDate}, function(err, res) {
if(err) {
console.log("Error " + err);
} else {
console.log("Updated Date for " + proj.title + " the date is " + stringDate);
}
});
}
数据如下所示,不会更改为字符串值:
"releaseDate": {
"$date": "2017-01-01T05:00:00.000Z"
},
现在我想弄清楚如何将日期更改为字符串...有一件事是我需要原始日期,因为我使用它来创建字符串,在我创建字符串后,我可以用日期替换日期字符串。