在Mongoose中引用对象时出错

时间:2018-06-19 17:46:26

标签: node.js mongodb mongoose

我在MongoDb的同一数据库中有两个不同的集合。我正在使用猫鼬来创建对象。我面临的问题是,当我使用createConnection时,相同的定义会给我带来错误Schema hasn't been registered for model "uniRoamStatus",而如果我只使用mongoose.connect(dburi),它就可以正常工作。

错误模型1定义

mongoose.model1.js

var mongoose = require('mongoose');
var config = require('../config.json');
var db = mongoose.createConnection(config.connectionString);
var uniRoamSchema = mongoose.Schema;

// create a schema
var uniRoamDetailsSchema = new uniRoamSchema({

createdDate: {
    type: Number,
    required: true,
},//mandatory
requestCompletionDate: {
    type: Number,
    required: true,
},
status: {
    type: uniRoamSchema.Types.ObjectId, 
    ref:'uniRoamStatus'
},
});
// we need to create a model using it
var uniRoamDetails = db.model('uniRoamDetails', uniRoamDetailsSchema, 
'uniRoamDetails');

// make this available to our users in our Node applications
module.exports = uniRoamDetails;

错误模型2定义

mongoose.model2.js

var mongoose = require('mongoose');
var config = require('../config.json');
var db = mongoose.createConnection(config.connectionString);

var Schema = mongoose.Schema;

// create a schema
var uniRoamStatusSchema = new Schema({
status: Number,
Description: String
});

// the schema is useless so far
// we need to create a model using it
var uniRoamStatus = db.model('uniRoamStatus', 
uniRoamStatusSchema,'uniRoamStatus');

// make this available to our users in our Node applications
module.exports = uniRoamStatus;

但是如果我改用mongoose.connect(uri)

,则相同的定义就可以很好地工作

正确的Model1定义

mongoose.model1.js
var mongoose = require('mongoose');
var config = require('../config.json');
mongoose.connect(config.connectionString);
var uniRoamSchema = mongoose.Schema;

// create a schema
var uniRoamDetailsSchema = new uniRoamSchema({

createdDate: {
type: Number,
required: true,
},//mandatory
requestCompletionDate: {
type: Number,
required: true,
},
status: {
type: uniRoamSchema.Types.ObjectId, 
ref:'uniRoamStatus'
},
});
// we need to create a model using it
var uniRoamDetails = mongoose.model('uniRoamDetails',uniRoamDetailsSchema, 
'uniRoamDetails');

// make this available to our users in our Node applications
module.exports = uniRoamDetails;

正确的Model2定义

mongoose.model2.js

var mongoose = require('mongoose');
var config = require('../config.json');
mongoose.connect(config.connectionString);

var Schema = mongoose.Schema;

// create a schema
var uniRoamStatusSchema = new Schema({
status: Number,
Description: String
});

// the schema is useless so far
// we need to create a model using it
var uniRoamStatus = mongoose.model('uniRoamStatus', 
uniRoamStatusSchema,'uniRoamStatus');

// make this available to our users in our Node applications
module.exports = uniRoamStatus;

即使我读到mongoose.connect(uri)在幕后使用mongoose.createConnection(uri),也有人可以向我解释为什么会有这种差异吗?

0 个答案:

没有答案