Riyas TK
Riyas TK

Reputation: 1251

mongoose db - array insertion using create and save

How to insert array and normal variable data to mongoose database..

var parent = new Parent({ children: [{ name: 'Matt' }, { name: 'Sarah' }], class: 10 })
parent.save(callback);

This is the method i know currently. I need it to be done from the req.body. So how can I done after creating the parent object. ie

var parent =  new Parent();
///code for inserting the array data and other normal datatypes 
parent.save(callback);

Upvotes: 0

Views: 39

Answers (1)

laggingreflex
laggingreflex

Reputation: 34627

Use the document instance like any other javascript object.

parent.children = [{ name: 'Matt' }, { name: 'Sarah' }];
parent.class = 10;
parent.save();

Just don't change it entirely (like doing parent = {...}), otherwise you'd have de-referenced the actual mongoose document instance. Only make changes on its properties like shown above.

Upvotes: 1

Related Questions