在节点中创buildmongoose模型的新实例 – 将第一项添加到其中一个embedded式数组中

这是我目前的代码:

假设我有以下mongoose模型:

// 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'}] })); 

我想在我的REST api中使用它,如下所示 – 在这段代码中,我本质上是试图创build一个汽车对象的实例,然后有传入的当前所有者id,是数组中的第一个项目“业主名单”

 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 }); } }); 

 owners : new Array(ObjectId.createFromHexString(req.body.ownerId)) 

小心不要在以后重写,只需按下即可。 从那里,它像往常一样业务…随意填充,操纵和保存。

ObjectId可以从Schema.types.ObjectId,IIRC获得。 如果您使用的是较旧版本的Mongo,则还可以使用fromHexString()