简体   繁体   中英

Mongoose get value from embedded document

在此处输入图片说明 i have a scheme like this

 var WFWorkItemDocument = new Schema({
        id: { type: String, required: true, unique: true, default: uuid.v1 },
        description: { type: String },
        period: [{
            id: { type: String, default: uuid.v1 },
            start: { type: Date, default: Date.now }
            due: { type: Number, integer: true },
            new: { type: Number, integer: true },
        }],

i want to get the period's due value for that i used a method like

    WorkItem.findOne({ id: idUpdate }, function(err, WorkItem) {
            if (err) {
                console.log("invlaid id");
                //return res.send(404, { error: 'invalid id' });
            }

            if (WorkItem) {
                console.log("id");
                console.log(WorkItem.period.due);

            } else {
                //res.send(404, new Error('Workitem not found'));
            }
});

but it doesn't work how can i get the due value??

This is the result for console.log(WorkItem)

Change the schema to embed one object. Unless you need embedded array.

 var WFWorkItemDocument = new Schema({
        id: { type: String, required: true, unique: true, default: uuid.v1 },
        description: { type: String },
        period: {
            id: { type: String, default: uuid.v1 },
            start: { type: Date, default: Date.now }
            due: { type: Number, integer: true },
            new: { type: Number, integer: true },
        },

And if you define it as an embedded array, you can access like :

WorkItem.period[index].due

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM