我在Node中收到这样的错误:
TypeError: Argument must be a string
at TypeError (native)
at Buffer.write (buffer.js:791:21)
at serializeObjectId
<snip>
条件是在使用MongoDB执行查找操作时ObjectID的一些用法。 ObjectID的一些用法引发了这个错误,有些则没有。唯一重要的是ObjectID的来源。如果它是从现有的集合中提取的,那就有效了。如果我自己生成它(例如,使用ObjectID.createFromHexString),它就会失败,如上所述。
答案 0 :(得分:4)
将mongodb版本更改为2.1.6。
答案 1 :(得分:2)
我花了几个小时跟踪这个。问题归结于我对Mongoose的使用。我正在使用Mongoose模式来处理我的一些收藏,而不是将Mongoose用于其他收藏。这是包含我有问题的代码的文件:
// Some common MongoDb operations and data.
'use strict';
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var logger = require('./Logger');
var mongoose = require('mongoose');
// TODO: Take this out for production.
mongoose.set('debug, true');
var PSSharingInvitations = require('./PSSharingInvitations')
var connectedDb = null;
// Call this just once, at the start of the server.
// TODO: Need better error handling when can't initially connect. Right now have an ugly looking error when Mongo is not already started and we try to start our server.
exports.connect = function(mongoDbURL) {
MongoClient.connect(mongoDbURL, function(err, db) {
assert.equal(null, err);
if (!db) {
logger.error("**** ERROR ****: Cannot connect to MongoDb database!");
}
else {
mongoose.connect(mongoDbURL);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// SCHEMA's
exports.SharingInvitation = PSSharingInvitations.buildSchema(mongoose);
logger.info("Mongoose: Connected to MongoDb database");
});
connectedDb = db;
logger.info("Mongo: Connected to MongoDb database");
}
});
};
exports.db = function () {
return connectedDb;
};
// Call this just once, when the server shuts down.
exports.disconnect = function() {
};
问题结果是:
connectedDb = db;
db是mongoose.connection
。也就是说,我使用mongoose.connection
作为我的数据库,用于未使用Mongoose的MongoDB集合。这导致间歇性错误。
修订后的(以及迄今为止的工作!)代码如下:
exports.connect = function(mongoDbURL) {
MongoClient.connect(mongoDbURL, function(err, db) {
assert.equal(null, err);
if (!db) {
logger.error("**** ERROR ****: Cannot connect to MongoDb database!");
}
else {
connectedDb = db;
logger.info("Mongo: Connected to MongoDb database");
mongoose.connect(mongoDbURL);
var connectedMongooseDb = mongoose.connection;
connectedMongooseDb.on('error', console.error.bind(console, 'connection error:'));
connectedMongooseDb.once('open', function() {
// SCHEMA's
exports.SharingInvitation = PSSharingInvitations.buildSchema(mongoose);
logger.info("Mongoose: Connected to MongoDb database");
});
}
});
};