Reputation: 1343
Here is my current code :
Assume I have the following mongoose model :
// This is the car model.
var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var Schema = mongoose.Schema;
// Setup a mongoose model, and pass it to module.exports.
module.exports = mongoose.model('Car', new Schema({
manufacturer: String,
model: String,
owners: [{type: ObjectId, ref: 'Owner'}]
}));
And I want to use it in my REST api as follows - In this code I am essentially trying to create an instance of the car object, and then have the current owner id which is passed in, be the first item in the array for the "list of owners"
app.post('/cars/create', function(req,res){
if( req.body.manufacturer && req.body.model && req.body.ownerId)
{
newCar = new Car(
manufacturer: req.body.manufacturer,
model: req.body.model,
owners: // NOT SURE WHAT TO DO HERE
});
}
});
Upvotes: 1
Views: 1301
Reputation: 331
owners : new Array(ObjectId.createFromHexString(req.body.ownerId))
Be careful not to rewrite it later on, just push. From there, it's business as usual... Feel free to populate, manipulate and save.
ObjectId can be obtained from Schema.types.ObjectId, IIRC. If you're using some older version of Mongo, you can also use fromHexString()
.
Upvotes: 2