如何只显示最新的文档?
How do I only display the newest document?
我用 Mongoose 在 Node.JS/Discord.JS 上搜索一个文档,我让它排序 { date: -1 }
,它仍然发送数据库中最旧的文档。
这是我的代码,我做错了什么?
gLog.
findOne({ "GiveawayHostID": name }).
sort({ date: -1}).
exec(function (err, host) {
这是上面使用的模式:
const mongoose = require("mongoose");
const gLogSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
GiveawayHost: String,
GiveawayHostID: String,
Prize: String,
WinnerUsername: String,
WinnerUsernameID: String,
time: String
});
module.exports = mongoose.model("GiveawayLogs", gLogSchema)
您的架构中似乎没有 date
字段,因此 mongoose 无法按日期排序。您可以按时间排序:
findOne({ "GiveawayHostID": name }).
sort({ time: -1}).
exec(function (err, host) {
但是,这可能不会 return 预期的结果,因为您的 time
字段被标记为 String
。所以猫鼬会按字母顺序对你的时间进行排序。
要解决此问题,您可以将 time
变量更改为 timestamp
格式。否则,您需要将 date
字段添加到您的架构中并遵循 this example.
您可以按 _id 字段对其进行排序,这是一个以时间戳开头的 BSON 数据类型,因此您可以按插入时间戳对其进行排序,这将始终为您提供最新记录如果您不创建自定义 _id,让 mongodb 创建一个查看更多信息 here
所以你所要做的就是:
findOne({ "GiveawayHostID": name }).
sort({ _id: -1}).
exec(function (err, host) {
仅引用文档中的重要部分:
ObjectIds are small, likely unique, fast to generate, and ordered.
ObjectId values consist of 12 bytes, where the first four bytes are a
timestamp that reflect the ObjectId’s creation. Specifically:
- 4-byte value representing the seconds since the Unix epoch,
- 5-byte random value, and
- 3-byte counter, starting with a random value.
我用 Mongoose 在 Node.JS/Discord.JS 上搜索一个文档,我让它排序 { date: -1 }
,它仍然发送数据库中最旧的文档。
这是我的代码,我做错了什么?
gLog.
findOne({ "GiveawayHostID": name }).
sort({ date: -1}).
exec(function (err, host) {
这是上面使用的模式:
const mongoose = require("mongoose");
const gLogSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
GiveawayHost: String,
GiveawayHostID: String,
Prize: String,
WinnerUsername: String,
WinnerUsernameID: String,
time: String
});
module.exports = mongoose.model("GiveawayLogs", gLogSchema)
您的架构中似乎没有 date
字段,因此 mongoose 无法按日期排序。您可以按时间排序:
findOne({ "GiveawayHostID": name }).
sort({ time: -1}).
exec(function (err, host) {
但是,这可能不会 return 预期的结果,因为您的 time
字段被标记为 String
。所以猫鼬会按字母顺序对你的时间进行排序。
要解决此问题,您可以将 time
变量更改为 timestamp
格式。否则,您需要将 date
字段添加到您的架构中并遵循 this example.
您可以按 _id 字段对其进行排序,这是一个以时间戳开头的 BSON 数据类型,因此您可以按插入时间戳对其进行排序,这将始终为您提供最新记录如果您不创建自定义 _id,让 mongodb 创建一个查看更多信息 here
所以你所要做的就是:
findOne({ "GiveawayHostID": name }).
sort({ _id: -1}).
exec(function (err, host) {
仅引用文档中的重要部分:
ObjectIds are small, likely unique, fast to generate, and ordered. ObjectId values consist of 12 bytes, where the first four bytes are a timestamp that reflect the ObjectId’s creation. Specifically:
- 4-byte value representing the seconds since the Unix epoch,
- 5-byte random value, and
- 3-byte counter, starting with a random value.