我有一个典型的Node.js,express,mongoDB和mongoose应用程序。
我试图实现mongoose-observer库来监听我的mongodb上的更改。 请参见网站:https://www.npmjs.com/package/mongoose-observer
添加此代码时(几乎与提供的示例完全相同):
mongooseObserver.register('MessageModel', 'create', function(newMessage) {
console.log("New Message!");
console.log(newMessage);
});
我收到以下错误:
node_1 | /home/app/chat/node_modules/mongoose/lib/index.js:362
node_1 | throw new mongoose.Error.MissingSchemaError(name);
node_1 | ^
nodered_1 | 28 Mar 07:32:11 - [info] Starting flows
mongo_1 | 2017-03-28T07:32:04.562+0000 I NETWORK [thread1] waiting for connections on port 27017
node_1 | MissingSchemaError: Schema hasn't been registered for model "MessageModel".
node_1 | Use mongoose.model(name, schema)
node_1 | at Mongoose.model (/home/app/chat/node_modules/mongoose/lib/index.js:362:13)
node_1 | at registerPre (/home/app/chat/node_modules/mongoose-observer/index.js:9:27)
node_1 | at Object.register (/home/app/chat/node_modules/mongoose-observer/index.js:38:9)
node_1 | at module.exports (/home/app/chat/app/routes.js:35:22)
node_1 | at Object.<anonymous> (/home/app/chat/server.js:83:24)
node_1 | at Module._compile (module.js:409:26)
node_1 | at Object.Module._extensions..js (module.js:416:10)
node_1 | at Module.load (module.js:343:32)
node_1 | at Function.Module._load (module.js:300:12)
node_1 | at Function.Module.runMain (module.js:441:10)
node_1 | at startup (node.js:134:18)
node_1 | at node.js:962:3
mongo_1 | 2017-03-28T07:32:11.604+0000 I NETWORK [thread1] connection accepted from 172.25.0.1:51800 #1 (1 connection now open)
只有在添加mongoose-observer代码时才会出现此错误,但这样做不会很好。
其他可能相关的代码
var mongooseObserver = require('mongoose-observer');
var mongoose = require('mongoose');
var bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10;
mongoose.connect('mongodb://mongo:27017/LoRaMessages'); //database name
var messageSchema = mongoose.Schema({
DevEUI: String,
LoRaPayload: String,
Header: String,
Longitude: Number,
Latitude: Number,
PDOP: Number,
TMG: Number,
SOG: Number,
Temparature: Number,
Time: String,
ServerTime: Number,
type: String,
deviceType: String,
batteryLevel: String,
JoinedAndBeeperStatus: String,
EnabledFlags: Number,
AlarmFlags: Number,
T_Temp: Number,
H_Humi: Number,
One_Temp: Number,
Two_Temp: Number,
_msgid: String
});
var MessageModel = mongoose.model('loramessages', messageSchema); //collection name
mongooseObserver.register('MessageModel', 'create', function(newMessage) { //it fails on this line
console.log("New Message!");
console.log(newMessage);
});
我知道这个图书馆并没有被很多人使用,但也许我错过了一些明显的东西。
我看到其他帖子包含此错误,但似乎还有另一个问题,因为这只会在实现特定库代码时发生。
感谢任何帮助。
编辑:虽然@Love-Kesh的答案是正确的。我发现这个库仅用于侦听Node.js中的更改,未检测到外部添加的数据。
答案 0 :(得分:1)
在Observer.register中传递'loramessages'而不是'MessageModel'
如果您使用“保存”创建新项目,则不会触发,请使用Model.create({})创建新记录。
//尝试在那里使用Save事件监听器
Observer.register('loramessages', 'save', function(createdUser){
// this callback will be executed when a new user is created
// Do something here, for example, send a email to the created user
});