Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing model parameters into a mongoose model

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

var exampleSchema = mongoose.Schema({
   name: String,
   <some more fields>
   userId: { type:mongoose.Schema.Types.ObjectId, ref: 'User' }
});

var Example = mongoose.model('Example', userSchema)

When I instantiate a new model I do:

// the user json object is populated by some middleware 
var model = new Example({ name: 'example', .... , userId: req.user._id });

The model's constructor takes a lot of parameters which has become tedious to write and refactor when the schema changes. Is there way of doing something like:

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

Or is the best way to create a helper method to generate a JSON object or even attach the userId to the request body? Or is there way that I haven't even thought of?

like image 903
Clive Avatar asked Feb 19 '13 13:02

Clive


People also ask

What is the difference between a Mongoose schema and model?

A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

What is the difference between id and _ID in Mongoose?

So, basically, the id getter returns a string representation of the document's _id (which is added to all MongoDB documents by default and have a default type of ObjectId ). Regarding what's better for referencing, that depends entirely on the context (i.e., do you want an ObjectId or a string ).

What does $Set do in Mongoose?

The $set operator replaces the value of a field with the specified value. The $set operator expression has the following form: { $set: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.

What is third parameter in Mongoose model?

ref is part of Mongoose's support for reference population. The third parameter to mongoose. model is an explicit collection name.


2 Answers

_ = 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 }))
like image 167
Jean-Philippe Leclerc Avatar answered Sep 23 '22 20:09

Jean-Philippe Leclerc


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.

like image 42
gustavohenke Avatar answered Sep 20 '22 20:09

gustavohenke