简体   繁体   中英

Mongoose is saving only objectId instead of the whole object

I am trying to save array of objects, but it is just saving the ObjectIds instead of whole objects, even thought in schema there is no refference or something like that.

So, I have this schema:

let MatchPlayerSchema = new Schema({
    deck: {type: Array, default: []}
});

And I am trying to save this array tooken from database ( playerDeck ):

    [ { _id: 5a1fc7ee667b103aace5f3ec,
    magicResist: 10,
    armor: 10,
    attack: 10,
    health: 10,
    name: 'Test',
    __v: 0,
    type: 'CardUnit' },
  { _id: 5a1fc7ee667b103aace5f3ec,
    magicResist: 10,
    armor: 10,
    attack: 10,
    health: 10,
    name: 'Test',
    __v: 0,
    type: 'CardUnit' }]

Like this:

let player = new MatchPlayer();
player.deck = playerDeck;
player.save();

However, the result is:

"deck" : [ 
     ObjectId("5a1fc7ee667b103aace5f3ec"), 
     ObjectId("5a1fc7ee667b103aace5f3ec")
]

I have tried to set deck to: [Schema.Types.Mixed] , but it didnt not help either.

When I try to save something just like: ['test', 'test'] , it saves alright.

I just can not figure out, what am I doing wrong.
Any ideas? Thank you

let MatchPlayerSchema = new Schema({
    deck: {
        type: Schema.Types.Mixed
    }
});

You should be able to store an array of objects into 'deck'

I had the same issue and setting the

mongoose.set('debug', true);

helped me to see what mongoose actually sending to the DB.

I was having in the Schema

const ChatSchema = mongoose.Schema({
    messages: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Message',
    }],
    isRemoved: {
        type: Boolean,
        default: false,
        required: true
    }
});

After switching the type to mongoose.Schema.Types.Mixed it worked perfectly. This is how I was invoking an update

Chat.findOneAndUpdate({ _id: req.params.chatId }, { $push: { messages: message }},{new: true});

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