【问题标题】:Mongoose query within the same schema同一架构中的 Mongoose 查询
【发布时间】:2017-06-21 19:09:06
【问题描述】:

是否可以在同一架构中执行查询? 例如,如果我有一个包含 2 个日期字段的架构,并且我需要找到一个日期字段大于另一个的数据。 这是我的架构和代码示例。

var Schema = mongoose.Schema;

var someSchema = new Schema({
	  someId	         :		{ type: String, default: '' ,index:true, unique: true  },
	  userName			:		{ type: String, default: ''},
	  fullName			:		{ type: String, default: '' },
	  created   			: 		{type: Date, default:''},
	  lastUpdated  			: 		{type: Date, default:''},
	  primaryGroupId		: 		{type:String,default:''},
	  nextHearing  			: 		{type: Date, default:''},
	  status			: 	{type:String,default:'open'},
	  
});



mongoose.model('Problem', someSchema);

下面的代码是我的查询。

var problemModel = mongoose.model('Problem');

var today = Date.now();

problemModel.find({$and:[{'nextHearing':{$lte: today}},{'nextHearing':{$gte : 'lastUpdated'}}]},function(err, result){

当我运行程序时,我得到以下错误

{ 消息:'在路径 "nextHearing" 中,值 "lastUpdated" 的转换失败', 名称:'CastError', 类型:'日期', 值:'lastUpdated', 路径:'nextHearing' }

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    new Date() 以 Date 对象的形式返回当前日期。 mongo shell 使用 ISODate 助手包装 Date 对象。 ISODate 采用 UTC。

    所以你可能需要改变:

    var today = Date.now();
    

    var today = new Date().toISOString();
    

    另外,看看this

    【讨论】:

    • 我认为这不是问题所在。我也尝试使用您的代码。错误在于这个{'nextHearing':{$gte : 'lastUpdated'}}
    • nextHearinglastUpdated 都是相同模式的字段,是否可以像我一样比较它们?如果没有,可能的解决方案是什么?
    猜你喜欢
    • 2017-01-13
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2011-08-27
    相关资源
    最近更新 更多