MongoDB查询字符串与来自角度前端的ISODate

MongoDB query string with ISODate from the angular front end

本文关键字:前端 ISODate 查询 字符串 MongoDB      更新时间:2023-09-26

我有一个mongoDB模型查询Model.find(query),我想以灵活的方式使用它。我的想法是传入查找模型特定实例可能需要的任何对象。就我而言,我正在寻找给定日期之前的实例,例如:

db.model.find({"date": {"$lt": ISODate('2016-02-11T19:00:38.702Z')}})

这段代码完美无缺。我遇到的问题是相同的创建/字符串化。在前端,我会做这样的事情:

{date: {$lt: 'ISODate("'(new Date()).toISOString()+'")'}}

问题是 ISODate 需要在查询中不带引号。有关如何在 GET 请求中传输此查询的任何线索?

您只需要将Date字符串发送到服务器,在那里您可以将其转换为ISODate

从客户端:

// 1. stringify the date
var currentDate = (new Date()).toISOString();
// 2. send the date in a request
// This example sends the string via the query parameter 'currentDate'

在服务器上:

db.model.find({"date": {"$lt": ISODate(req.query.currentDate)}})