简体   繁体   中英

mongoose: Insert a subdocument NOT an array

I am struggling to insert a document inside another document. I've looked at all the entries like this but they aren't quite what I am looking for.

Here is the scenario:

I have a common document that has its own schema. Lets call it a related record:

(function(){
    'use strict';

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;

    var relatedRecordSchema = new Schema({
        params: {
            recordId: Schema.Types.ObjectId,
            recordType: String,
            recordTitle: String
        },
        metadata: {
            dateCreated: {type: Date, default: Date.now}
        }
    },{ _id : false });

    mongoose.model('RelatedRecord', relatedRecordSchema);

})();

I have no trouble inserting this in an ARRAY inside document that require it. Ie its configured this way:

        //Embedded
        relationships: {
            following: [mongoose.model('RelatedRecord').schema],
            followers: [mongoose.model('RelatedRecord').schema],
            blocked: [mongoose.model('RelatedRecord').schema]
        }

This works perfectly.

The scenario that does not work is where there is a single related record, lets say the source of a notification:

var notificationSchema = new Schema({
    params: {
        title: String,
        imageUrl: String,
        source: mongoose.model('RelatedRecord').schema
    },
    metadata: {
        dateCreated: { type: Date, default: Date.now },
        dateViewed: Date
    }
});

So when I am creating the notification I try and assign the previously prepared RelatedRecord

returnObj.params.source = relatedRecord;

The record appears during a debug to be inserted (it is inside a _docs branch but far deeper than I would expect) but when the object is saved (returnObj.save()) the save routine is abandoned without error, meaning it does not enter into the callback at all.

So it looks to me that i'm confusing mongoose as the dot assignment is forcing the subdoc into the wrong location.

So the question is simple:

How do I set that subdocument?

What the question isn't:

No I don't want to populate or advice on how you would solve this problem differently. We have sensible reasons for doing things how we are doing them.

Cheers b

As Hiren S correctly pointed out:

1) Sub-Docs = array, always. Its in the first line in the docs :|

2) By setting the type to mixed, assignment of the object worked.

I'm a dumdum.

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