草庐IT

node.js - 架构无效,应为 `mongodb` 或 `mongodb+srv`

coder 2023-11-05 原文

有一个问题,一个项目简单的 Node js 应用程序从用户添加和获取数据并保存到 mongo(使用 3..ver),一切正常(保存,获取等),示例是

var express = require('express');
var router = express.Router();
var mongo = require('mongodb').MongoClient;
var objectID = require('mongodb').ObjectID;
var assert = require('assert');

const url = 'mongodb://localhost:27017';
const dbName = 'ldex';
const tblOffers = 'offers';

router.post('/insert', function (req, res, next) {
    var order = {
        type: 'Sell',
        ..............
        max: req.body.max,
        protection: req.body.protection,
        comment: req.body.comment,
        date: new Date().toDateString()
    };

    mongo.connect(url, function (err, client) {
        assert.equal(null, err);

        const db = client.db(dbName);

        db.collection(tblOffers).insertOne(order, function (err, res) {
            assert.equal(null, err);
            console.log('Offer placed');
            client.close();
        })
    });

    res.redirect('/exchange')
});

但这是另一个应用程序,解析器,具有相同的 mongo 连接,它从其他网站添加一些数据(当不使用 mongo 时一切正常,我收到数据很好),这是代码的一部分:

...
let assert = require('assert');
let mongo = require('mongodb').MongoClient;
let router = express.Router();

const url = 'mongodb://localhost:27017/';
const dbName = 'ceramo';
const tblOffers = 'items';

...

/*
 *  Get items from specific group
 */

function getGroupItems(url, callback) {
    request({uri: url}, function (error, response, body) {
        let list = [];
        let $ = cheerio.load(body);
        $('#tovar').find('a.cat_item_disc_a').each(function(i, elem) {
            list[i] = 'https://plitkazavr.ru' + $(this).attr('href');
        });
        callback(list);
    });
}

/*
 *  Parse one item from specific link
 */

function getItem(url) {
    request({uri: url}, function (error, response, body) {
        let list = {};
        let $ = cheerio.load(body);
        $('#item_border').find('> #item_prop > ul').find('li.item_list').each(function(i, elem) {
            list[$(this).find('.item_cell').first().text()] = $(this).find('div.item_cell.item_val').text();
        });
        list.price = (parseFloat($('#item_price').text()));
        list.img = ('https://plitkazavr.ru' + $('#item_img').attr('src'));
        list.meta = ($('#item_wrap').find('meta[itemprop="description"]').attr("content"));

        mongo.connect(url, function (err, client) {
            assert.equal(null, err);

            const db = client.db(dbName);

            db.collection(tblOffers).insertOne(order, function (err, res) {
                assert.equal(null, err);
                console.log('Offer placed');
                client.close();
            })
        });

    });
}

router.get('/parse', function (req, res, next) {

    getGroupItems('https://plitkazavr.ru/Naxos/Clio', function (items) {
        items.forEach(function(item, i, arr) {
            setTimeout(function() {
                getItem(item);
            }, 1000);
        });
    });

    res.end('ok');
});

连接断开并给出

`Error: Invalid schema, expected `mongodb` or `mongodb+srv

不明白哪里有问题,求助...

最佳答案

您的 MongoDB URL 似乎不完整,它应该包含您的 dbName,然后再像这样传递到 mongoose 连接中

const url = 'mongodb://localhost:27017/';
const fullUrl = url + dbName; // which should evaluate to this 'mongodb://localhost:27017/ceramo'


mongo.connect(fullUrl, function (err, client) {...}

关于node.js - 架构无效,应为 `mongodb` 或 `mongodb+srv`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48605217/

有关node.js - 架构无效,应为 `mongodb` 或 `mongodb+srv`的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  3. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  4. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  5. ruby - 如何排除无效日期 ruby - 2

    我想知道我应该引用什么异常名称。我的日期无效。我检查了文档,但找不到。BeginDate.new(day,month,year)Rescueexceptionnamestatements 最佳答案 我认为您正在寻找ArgumentError.使用irb:>Date.new(2,-200,3)ArgumentError:invaliddatefrom(irb):11:in`new'from(irb):11所以beginDate.new(2,-200,3)rescueArgumentError#yourlogicend

  6. arrays - Ruby 数组 += vs 推送 - 2

    我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“

  7. ruby - Ruby 和 Ruby on Rails 中的三层架构 - 2

    我是一名决定学习Ruby和RubyonRails的ASP.NETMVC开发人员。我已经有所了解并在RoR上创建了一个网站。在ASP.NETMVC上开发,我一直使用三层架构:数据层、业务层和UI(或表示)层。尝试在RubyonRails应用程序中使用这种方法,我发现没有关于它的信息(或者也许我只是找不到它?)。也许有人可以建议我如何在RubyonRails上创建或使用三层架构?附言我使用ruby​​1.9.3和RubyonRails3.2.3。 最佳答案 我建议在制作RoR应用程序时遵循RubyonRails(RoR)风格。Rails

  8. += 的 Ruby 方法 - 2

    有没有办法让Ruby能够做这样的事情?classPlane@moved=0@x=0defx+=(v)#thisiserror@x+=v@moved+=1enddefto_s"moved#{@moved}times,currentxis#{@x}"endendplane=Plane.newplane.x+=5plane.x+=10putsplane.to_s#moved2times,currentxis15 最佳答案 您不能在Ruby中覆盖复合赋值运算符。任务在内部处理。您应该覆盖+,而不是+=。plane.a+=b与plane.a=

  9. ruby - Sinatra + Heroku + Datamapper 使用 dm-sqlite-adapter 部署问题 - 2

    出于某种原因,heroku尝试要求dm-sqlite-adapter,即使它应该在这里使用Postgres。请注意,这发生在我打开任何URL时-而不是在gitpush本身期间。我构建了一个默认的Facebook应用程序。gem文件:source:gemcuttergem"foreman"gem"sinatra"gem"mogli"gem"json"gem"httparty"gem"thin"gem"data_mapper"gem"heroku"group:productiondogem"pg"gem"dm-postgres-adapter"endgroup:development,:t

  10. ruby-on-rails - Assets 管道损坏 : Not compiling on the fly css and js files - 2

    我开始了一个新的Rails3.2.5项目,Assets管道不再工作了。CSS和Javascript文件不再编译。这是尝试生成Assets时日志的输出:StartedGET"/assets/application.css?body=1"for127.0.0.1at2012-06-1623:59:11-0700Servedasset/application.css-200OK(0ms)[2012-06-1623:59:11]ERRORNoMethodError:undefinedmethod`each'fornil:NilClass/Users/greg/.rbenv/versions/1

随机推荐