收集后POST响应错误.插入NodeJS Mongo模块

POST response error after collection.insert with NodeJS Mongo module

本文关键字:插入 NodeJS Mongo 模块 错误 响应 POST      更新时间:2023-09-26

我在尝试POST 时遇到此错误

>         process.nextTick(function() { throw err; });
>                                       ^
>     
>     TypeError: first argument must be a string or Buffer
>         at ServerResponse.OutgoingMessage.end (_http_outgoing.js:524:11)

错误表明mongodb模块中的utilscursor都有问题,但它们是什么?

在GET上一切都很好,但在POST上停止了(邮递员和传递文本{"name":"Computer","price":2500})-我无法跟踪哪个模块或实例正在停止代码。

这是我与数据库的连接:

// Our primary interface for the MongoDB instance
var MongoClient = require('mongodb').MongoClient;
// Used in order verify correct return values
var assert = require('assert');
var connect = function (databaseName, callBack) {
    var url = 'mongodb://localhost:27017/' + databaseName;
    MongoClient.connect(url,
        function (error, database) {
            assert.equal(null, error);
            console.log("Succesfully connected to MongoDB instance!");
            callBack(database);
        });
};

exports.find = function (databaseName, collectionName, query, callback) {
    connect(databaseName, function (database) {
        var collection = database.collection(collectionName);
        collection.find(query).toArray(
            // Callback method
            function (err, documents) {
                // Make sure nothing went wrong
                assert.equal(err, null);
                // Print all the documents which we found, if any
                console.log("MongoDB returned the following documents:");
                console.dir(documents)
                callback(err, documents);
                // Close the database connection to free resources
                database.close();
            })
    })
};
exports.insert = function (databaseName, collectionName, object, callback) {
    connect(databaseName, function (database) {
        var collection = database.collection(collectionName);
        collection.insert(document, {w: 1}, function (err, documents) {
            console.log("Added a new document");
            console.log(documents[0]);
            callback(err, documents[0]);
        });
    })
};
exports.remove = function (databaseName, collectionName, object, callback) {
    connect(databaseName, function (database) {
        var collection = database.collection(collectionName);
        collection.remove(object, function (err, result) {
            callback(err, result);
            database.close();
        });
    })
};

这个问题实际上非常简单,所以我很惊讶你没有得到更好的错误消息。

在您的代码中:

collection.insert(document, {w: 1}, function (err, documents) {
  console.log("Added a new document");
  console.log(documents[0]); // I expect this to log undefined
  callback(err, documents[0]);
});

传递到collection.insert回调的第二个参数实际上是一个结果对象,而不是插入的文档。因此,documents[0]最终成为undefined,因为它不是一个文档数组。因此,当您尝试发送undefined作为响应时,它是失败的。

如果您打算传递新创建的文档,则必须使用result对象来获取_id并将其附加到插入的文档。

顺便说一句,我会考虑保持与数据库的连接打开,而不是每次您想与Mongo交谈时都创建一个新的连接。