Passing model parameters into a mongoose model

前端 未结 3 1314
走了就别回头了
走了就别回头了 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.

    0 讨论(0)
  • 2020-12-18 02:09

    Since Node 8.3, you can also use Object Spread syntax.

    var model = new Example({ ...req.body, userId: req.user._id });
    

    Note that order matters, with later values overriding previous ones.

    0 讨论(0)
  • 2020-12-18 02:19
    _ = require("underscore")
    
    var model = new Example(_.extend({ userId: req.user._id }, req.body))
    

    or if you want to copy userId into req.body:

    var model = new Example(_.extend(req.body, { userId: req.user._id }))
    
    0 讨论(0)
提交回复
热议问题