简体   繁体   中英

how to use population/ref save Schema in Mongoose

first have user, then create store . how to do create store and ref to User?

  • 1 user to many sotres
  • 1 store to 1 user

// Schema

 var UserSchema = new Schema({
     name: String,
     stores : [{ type: Schema.Types.ObjectId, ref: 'Store' }]
 });

 var StoreSchema = new Schema({
     name: String,
     user : [{ type: Schema.Types.ObjectId, ref: 'User' }] 
 });

 mongoose.model('Store', StoreSchema);
 mongoose.model('User', UserSchema);

// express/mongoose save()

exports.storeAdd = function (req, res) {

     new Store({
          name : 'store 1',
          user : [{_id:req.session._id}]
     }).save();

};

It's not working, plz help thx

var StoreSchema = new Schema({
  name: String,
  user : [{ type: Schema.Types.ObjectId, ref: 'User' }] 
});

This actually defines a one to many relationship between store and user as well. Is that intentional? If not you should remove the [, ] from around user, as well as in save().

Check to make sure that req.session._id has a valid mongoose Object ID, that is the mostly likely reason that the save is not working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM