mongoose 如何设置数组对象的 virtual ?
发布于 9 年前 作者 huydev 4491 次浏览 最后一次编辑是 8 年前 来自 问答

想把取出来的日期对象加工成字符串的形式设置到 virtual 里面。 代码如下:

var PostSchema = mongoose.Schema({
	name: String,
	title: String,
	post: String,
	createAt: {type: Date, default: Date.now},
	updateAt: {type: Date, default: Date.now},
	comments: [{
		name: String,
		email: String,
		website: String,
		time: {type: Date, default: Date.now},
		content: String
	}]
});

PostSchema.virtual('postTime').get(function(){
	return getDate(this.updateAt);
});
PostSchema.virtual('commentTime').get(function(){
	return getDate(this.comments.???);	//这里怎么取得time的值?
});

function getDate(date){
  var year = date.getFullYear(),
      month = date.getMonth(),
      day = date.getDate(),
      hours = date.getHours(),
      minutes = date.getMinutes(),
      seconds = date.getSeconds();
  return year + '-' + twonumber(month+1) + '-' + twonumber(day) + ' ' + twonumber(hours) + ':' +
          twonumber(minutes) + ':' + twonumber(seconds);
}
function twonumber(value){
  return value < 10 ? '0' + value : value;
}
3 回复

你这样是无解的 必须定义一个Sub doc 在sub doc中定义virtual 然后包含进来

var Comment = new Schema({
   		name: String,
        email: String,
        website: String,
        time: {type: Date, default: Date.now},
        content: String
});
Comment.virtual('commentTime').get(function() {
    return formatDate(this.time)
});
var PostSchema = mongoose.Schema({
    name: String,
    title: String,
    post: String,
    createAt: {type: Date, default: Date.now},
    updateAt: {type: Date, default: Date.now},
    comments: [Comment]
});

@LeafInStrom fromatDate在代码中并未定义 建议用moment来format

@LeafInStrom 谢谢 按照你说的果然可以。

回到顶部