我是Node.js和mongodb的新手。
在我的Node.js应用程序中,我正在使用mongodb和mongodb操作我正在使用mongoose。
在package.json
文件中,我有以下依赖项:
"mongoose": "4.11.9"
虽然我的应用程序有效(我可以做我想做的所有事情),但在服务器日志中我总是看到以下错误消息:
要创建新的ObjectId,请尝试使用
Mongoose.Types.ObjectId
使用Mongoose.Schema.ObjectId
。
我该如何解决这个问题?
答案 0 :(得分:2)
已修复mongoose 4.11.10
及更高版本,因此请尝试升级您的版本以消除警告。
这是#5571的无意副作用,因为employees.certifications
恰好是24个字符长。
var mongoose = require('mongoose');
var zoneSchema = new mongoose.Schema({
employees: {
certifications: {type: mongoose.Schema.Types.ObjectId, ref: 'Certifications'}
}
});
var certificationsSchema = new mongoose.Schema({
type: String,
list: [{type: mongoose.Schema.Types.ObjectId, ref: 'Certification'}]
});
var certificationSchema = new mongoose.Schema({
name: String
});
var Zone = mongoose.model('Zone', zoneSchema);
var Certifications = mongoose.model('Certifications', certificationsSchema);
var Certification = mongoose.model('Certification', certificationSchema);
var newZone = new Zone();
如需进一步阅读,请查看issue#5587& issue#5571
答案 1 :(得分:1)
您看到的是一条警告消息(与导致您的节点进程退出的错误相反)。
考虑这个例子:
#!/usr/bin/env node
'use strict';
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const conn = mongoose.connection;
const Schema = mongoose.Schema;
const schema = new Schema({
myRef: {
type: Schema.Types.ObjectId,
ref: 'someothercollection'
}
});
const Test = mongoose.model('test', schema);
const test = new Test({
myRef: Schema.ObjectId() // or Schema.Types.ObjectId()
});
const test2 = new Test({
myRef: mongoose.Types.ObjectId()
});
async function run() {
await conn.dropDatabase();
let doc = await test.save();
console.log(doc);
let doc2 = await test2.save();
console.log(doc2);
return conn.close();
}
run();
<强>输出:强>
stack: ./49841247.js
mongoose: To create a new ObjectId please try `Mongoose.Types.ObjectId` instead of using `Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if you're trying to create a hex char path in your schema.
Trace
at Function.ObjectId (/Users/lineus/dev/Help/mongoose5/node_modules/mongoose/lib/schema/objectid.js:30:13)
at Object.<anonymous> (/Users/lineus/dev/Help/mongoose5/stack/49841247.js:19:17)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
{ _id: 5ad33e173a19606ffa47c95c, __v: 0 }
{ _id: 5ad33e173a19606ffa47c95e,
myRef: 5ad33e173a19606ffa47c95d,
__v: 0 }
stack:
你可以看到:
如果您收到此警告,则很可能是您的代码中某处使用了错误的方法来生成objectId。
如果您没有错误地手动生成objectId,请查看the next answer at the time of this edit.