Mongoose Schema hasn't been registered for model

前端 未结 17 869
猫巷女王i
猫巷女王i 2020-11-27 15:00

I\'m learning the mean stack and when I try to start the server using

npm start

I get an exception saying that:

schema has         


        
17条回答
  •  囚心锁ツ
    2020-11-27 15:54

    IF YOU USE MULTIPLE mongoDB CONNECTIONS


    beware that when using .populate() you MUST provide the model as mongoose will only "find" models on the same connection. ie where:

    var db1 = mongoose.createConnection('mongodb://localhost:27017/gh3639');
    var db2 = mongoose.createConnection('mongodb://localhost:27017/gh3639_2');
    var userSchema = mongoose.Schema({
      "name": String,
      "email": String
    });
    
    var customerSchema = mongoose.Schema({
      "name" : { type: String },
      "email" : [ String ],
      "created_by" : { type: mongoose.Schema.Types.ObjectId, ref: 'users' },
    });
    
    var User = db1.model('users', userSchema);
    var Customer = db2.model('customers', customerSchema);
    

    Correct:

    Customer.findOne({}).populate('created_by', 'name email', User)
    

    or

    Customer.findOne({}).populate({ path: 'created_by', model: User })
    

    Incorrect (produces "schema hasn't been registered for model" error):

    Customer.findOne({}).populate('created_by');
    

提交回复
热议问题