Chr*_*nce 6 mongoose mongodb node.js
我在Node中遇到这样的错误:
TypeError: Argument must be a string
at TypeError (native)
at Buffer.write (buffer.js:791:21)
at serializeObjectId
<snip>
Run Code Online (Sandbox Code Playgroud)
条件是在使用MongoDB执行查找操作时ObjectID的一些用法.ObjectID的一些用法引发了这个错误,有些则没有.唯一重要的是ObjectID的来源.如果它是从现有的集合中提取的,那就有效了.如果我自己生成它(例如,使用ObjectID.createFromHexString),它就会失败,如上所述.
我花了几个小时才找到这个。问题归结于我对 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() {
};
Run Code Online (Sandbox Code Playgroud)
问题原来出在这一行:
connectedDb = db;
Run Code Online (Sandbox Code Playgroud)
其中 db 是mongoose.connection. 也就是说,我使用mongoose.connectionMongoDB Collections 作为我的数据库,但未使用 Mongoose。这导致了间歇性错误。
修改后的(到目前为止有效!)代码如下:
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");
});
}
});
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3011 次 |
| 最近记录: |