简体   繁体   中英

insert document into mongodb array using mongoose, nodejs

I want to insert a record into an mongoDB. DB Model is as:

var stockhistory = new Schema({
symbol:   String,
values:   [{
    date:     Date,
    open:     Number,
    close:    Number,
    high:     Number,
    low:      Number,
    adjClose:Number,
    volume:   Number
    }]
});

I want to insert new document to values array.

I have tried the following but getting error.

var insertObj = {
    'date': obj[0].lt,
    'open': obj[0].op,
    'close': obj[0].l,
    'high': obj[0].hi,
    'low': obj[0].lo,
    'adjClose': obj[0].l_fix,
     'volume': obj[0].vo
 };
var sname = 'symbol';
var History = require('../model/stockHistory');
var history = new History({ symbol: sname, values: insertObj });
history.save(function(err) {
    if (err) {
        return err;
    } else {
        console.log("Quote saved");
    }
});

And

History.findOneAndUpdate(
                                {symbol: sname},
                                {$push: {values: insertObj}},
                                {safe: true, upsert: true},
                                function(err, model) {
                                    console.log(err);
                                }

I am not sure about the document insert into array and tried above after searching on google but not getting through.

Thanks for help !

Edit

Records are successfully created now but new records are created as a document but not under values array.Please have a look at screenshot(link given below)

I want to create new record in values so that count after creation will be 2696 instead it created new separate document. screenshot

On your schema, values is an array, but when you do:

var history = new History({ symbol: sname, values: insertObj });

You are setting values as an object. You could try:

var insertObj = {
    'date': obj[0].lt,
    'open': obj[0].op,
    'close': obj[0].l,
    'high': obj[0].hi,
    'low': obj[0].lo,
    'adjClose': obj[0].l_fix,
     'volume': obj[0].vo
   };
var sname = 'symbol';
var History = require('../model/stockHistory');
var history = new History({ symbol: sname, values: insertArr });
History.findOneAndUpdate(
   {symbol: sname},
   {$push: {values: insertObj}},
   {safe: true, upsert: true},
   function(err, model) {
    console.log(err);
  }

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