Mongoose, CastError: Cast to Array failed for value when trying to save a model that contains a model

后端 未结 7 1531
日久生厌
日久生厌 2020-12-09 14:52

I am trying to create the model for my mongodb database using mongoose. This is what I am trying to do:

var Class = mongoose.model(\'Class\', {className: St         


        
相关标签:
7条回答
  • 2020-12-09 15:51

    Your model definition is incorrect, you should fix like below.

    // var Schema = mongoose.Schema;
    var User = mongoose.model('User',{ 
      email: String, 
      classes: [ {type: Schema.Types.ObjectID, ref: 'Class'}] 
    });
    
    var Class1 = new Class({/*yourDataWillBeHere*/})
    
    Class1.save(function(err, classData) {
       var User1 = new User({/*YourDataWillBeHere*/})
       User1.classes.push(classData._id);
       User1.save(function(err, userData) {
          //make something with userData object 
       })
    })
    

    Then you can get fetched data using with populate() like this

    User
    .find()
    .populate('classes')
    .exec()
    
    0 讨论(0)
提交回复
热议问题