Passing model parameters into a mongoose model

前端 未结 3 1335
走了就别回头了
走了就别回头了 2020-12-18 01:26

I have a mongoose model that has an association with a user model e.g.

var exampleSchema = mongoose.Schema({
   name: String,
   
           


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-18 02:08

    If I understood you correctly, you'll be good trying the following:

    // We "copy" the request body to not modify the original one
    var example = Object.create( req.body );
    
    // Now we add to this the user id
    example.userId = req.user._id;
    
    // And finally...
    var model = new Example( example );
    

    Also, do not forget to add in your Schema options { strict: true }, otherwise you may be saving unwanted/attackers data.

提交回复
热议问题