如何保存子文档对象Id,其中很少有字段与mongoose?

时间:2016-02-11 10:20:46

标签: node.js mongodb mongoose mongoose-schema

我想保存Tower obj和flat obj。 Tower Schema

var TowerSchema = new Schema({
name:String,
project:{type:mongoose.Schema.ObjectId, ref:"Project"},
total_unit:Number,
sold_unit:Number,
flats:[{type:mongoose.Schema.ObjectId, title:String, ref:'Flat'}],
createdAt: { type: Date, 'default': Date.now }
});

Flat Schema

var flatSchema = new Schema({
year: Number,
title:String
})

我想用mongoose save

保存它
var flats1 = new sampleModel({
        title: objTitle,
    });

    flats1.save(function (err) {
        if (err) { 
            console.log('msg: '+err)
        } else {
            console.log('msg: '+flats1)
        }
    });

   var objId = flats1.objectId
    var objTitle = flats1.title

    var newTower = new TowerModel({
        name:towerName,
        project:null,
        total_unit:totalUnit,
        sold_unit:soldUnit,
        flats: [{objId , objTitle }],
        createdAt: { type: Date, 'default': Date.now }
    });

我的输出应该是这样的

{
    "_id" : ObjectId("56bc5da2dc4a3d1c1b00000f"),
    "name" : "sample name five",
    "project" : null,
    "total_unit" : 3,
    "sold_unit" : 3,
    "createdAt" : ISODate("2016-02-11T10:08:34.309Z"),
    "flats" : [ 
       "title":sample,
       "_id":"flats id"
],
    "__v" : 0
}

我是mongoose和Node的初学者。请帮帮我。

0 个答案:

没有答案