【问题标题】:Attempt to search for a specific string尝试搜索特定字符串
【发布时间】:2020-05-05 15:40:40
【问题描述】:

我正在尝试根据用户的消息在数据库中查找特定行,即:catalystname

在架构中,我已成功地将给定的字符串索引为文本:


const { Schema } = mongoose;

const scheduleMessageSchema = new Schema({
    _id: { type: Schema.Types.Oid, auto: true },
    catalystname: String,
    catalystdesc: String,
    catalystquest: String,
    date: String,
});

scheduleMessageSchema.index({catalystname: 'text'});
module.exports = mongoose.model('dbcatalyst', scheduleMessageSchema);

我的搜索码:

const Catal = require("../src/models/dbcatalyst.js")


module.exports.run = async (client, message, args) => {

    message.content = args.slice(0).join(" ")


        Catal.find({$text: {$search: message.content}})
        .exec(function(docs){

        let embedlogs3 = new Discord.RichEmbed()
            .setAuthor(`1`, message.author.displayAvatarURL)
            .setDescription(`${docs}`)
            .setColor("#33ffff")

        message.channel.send(embedlogs3)
        /*/ ${collected.first().content}/*/
    });


}

并开始在消息中搜索所需的行。机器人成功地完成了它的任务,但是完整地显示了整个文档而不是 1 行。

_id: 5e243704961eb23c106bfb02,
catalystname: 'Чёрный Коготь',
catalystdesc: '0',
catalystquest: '0',
date: '1579430157018',
__v: 0
}

我能以某种方式准确地输出字符串吗? catalystname

【问题讨论】:

  • 欢迎来到 StackOverflow。您是否尝试过使用docs.catalystname
  • @ChrisSatchell TypeError: Cannot read property 'catalystname' of null
  • 什么是docs?是对象还是数组?
  • @ChrisSatchell 对象,可能。

标签: javascript mongodb mongoose discord discord.js


【解决方案1】:

查看 Mongoose 文档,回调似乎需要 两个 参数:

  1. err 错误或为空
  2. docs返回的文件

将您的回调更改为

Catal.find({$text: {$search: message.content}})
  .exec(function(err, docs){
    ...
  });

您应该会收到一组匹配的文档。

【讨论】:

  • 没错,我得到了必要的数组,但是现在我需要从这个数组中找到字符串catalystname。我尝试这样做docs.catalystname,但控制台抛出错误:(node:8904) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.,输出:undefined
  • 您正在寻找docs[index].catalystname,其中index 是您正在寻找的项目的索引(在这种情况下可能是0
  • docs['text'].catalystname 对吗?我只是不太明白它是如何工作的。
  • 您可能想先了解基础知识,然后再深入研究并创建机器人:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
猜你喜欢
  • 1970-01-01
  • 2017-09-18
  • 2011-12-16
  • 1970-01-01
  • 1970-01-01
  • 2013-01-20
  • 2018-11-24
  • 2018-10-18
  • 2013-03-02
相关资源
最近更新 更多