1

I am trying to insert a sub document into all existing documents in a collection in db,in nodejs using express framework.Following is the code snippet:

updatedoc: function(update,options,cb)
{
   return this.update({},update,options).exec(cb); 
}

where parameters update and options are as follows :

const update = { $push: { "defaultads": content }};
const options = { multi: true};

It seems to run and gives the following output on the console : { n: 1, nmodified: 1, ok: 1 }

but no push takes place at all ,in any of the documents of the database. I have checked : 1) whether i am pushing in the right db. 2) whether correct values are being passed However I am not able to find where I am going wrong.

I am new to nodejs and would really appreciate guidance in solving this problem. Thanks in advance.

parwatcodes
  • 6,669
  • 5
  • 27
  • 39

1 Answers1

0

I am giving a simple code with full fledged requirement of yours. First create a config.js using this file you will be connected to mongodb.Here is the code

module.exports = {
    'secretKey': '12345-67890-09876-54321',
    'mongoUrl' : 'mongodb://localhost:27017/product'
}

Next create a models folder . Keep this schema in this models folder . I named it as product.js. Here is the code

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imageSchema = new Schema({
imagepath:{
    type:String
}
});
var nameSchema = new mongoose.Schema({

productName:{type: String},
productPrice:{type: Number},
imagePaths:[imageSchema]
});
module.exports  = mongoose.model("product", nameSchema);

Next create a routes folder and keep this routes code in this folder I named it as route.js. Here is the code

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var Product = require('../models/product');
var app = express();
var Router = express.Router();
Router.use(bodyParser.json());

Router.get('/product',function(req,res){
 Product.find({}, function (err, product) {
        if (err) throw err;
        res.json(product);
    });
})  
Router.post('/productData',function(req, res, next){
    Product.create(req.body, function (err, product) {
        if (err) throw err;
        console.log('Product Data created!');
        var id = product._id;

        res.writeHead(200, {
            'Content-Type': 'text/plain'
        });
        res.end('Added the product data with id: ' + id);
    });    
})

Router.post('/subdocument',function (req, res, next) {
Product.find({},function (err, result) {
        if (err) throw err;
        for(var i=0;i<result.length;i++){
        result[i].imagePaths.push(req.body);
        result[i].save(function (err, ans) {
            if (err) throw err;
            console.log('SubDocument created!');
          });
        }
        res.send("Successfully added");
    });
})  
    module.exports = Router;

Next server code I named it as app.js. Here is the code

var express = require('express');
var bodyParser = require('body-parser');
var Product = require('./models/product');
var mongoose = require('mongoose');
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log("Connected correctly to server");
});
var app = express();
var route=require('./routes/route');
app.use('/route',route);
    app.listen(3000,function(){
    console.log("Server listening on 3000");
});

Run the server as node app.js.

API's

  1. Use GET method http://localhost:3000/route/product .This is for getting all the product information.

  2. Use POST method http://localhost:3000/route/productData .This for creating document. Post data in json format through request body like

    {

    "productName" : "sweets", "productPrice" : "33"

    }

You will see the response like this.

enter image description here First post some documents i.e., post 2 or 3 documents and then you can see the documents with get API as I mentioned above. Then you will see all the documents contains empty sub document. You will see the response like this

enter image description here

And now add the sub document to all using the below api.

  1. Use POST method http://localhost:3000/route/subdocument . Using this you can add a sub document to all the documents like this you need to add sub document

    {

    "imagepath" : "desktop"

    }

You can see the response like this

enter image description here

After this again when you run the get API you can see all the sub documents are added to all documents.

enter image description here

Hope this helps.

Syed Ayesha Bebe
  • 1,797
  • 1
  • 15
  • 26
  • Thank you so much for putting in so much of efforts :), How ever I have done as above ,but it just gets first document in the database in the result and does not enter in any document:(. .Where am i going wrong? its pretty straight forward. – RIMSH TASNEEM Sep 08 '17 at 07:25
  • Any ways, I have resolved the issue . My code is working now :) Thank you for your help Syeda Ayesha Bebe – RIMSH TASNEEM Sep 08 '17 at 08:09
  • Ayesha Bebe -Your answer did not help me to solve my problem .if you want it to be accepted just for the sake of it . then fine . – RIMSH TASNEEM Sep 08 '17 at 10:27
  • This code is as per your requirement why this code doesn't help you is this is not your requirement????? – Syed Ayesha Bebe Sep 08 '17 at 10:30