无法使用nodejs在db中的所有文档中插入子文档

时间:2017-09-07 04:56:58

标签: node.js mongodb express

我正在尝试使用express框架在nodejs中的db中的集合中的所有现有文档中插入子文档。以下是代码片段:

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

其中参数更新和选项如下:

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

它似乎运行并在控制台上提供以下输出:     { n: 1, nmodified: 1, ok: 1 }

但在数据库的任何文档中根本没有推送。 我检查过 : 1)我是否正在推进正确的数据库。 2)是否传递了正确的值 但是我无法找到我错的地方。

我是nodejs的新手,非常感谢解决这个问题的指导。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

我正在给出一个简单的代码,满足您的全面要求。首先使用此文件创建一个config.js,您将连接到mongodb.Here是代码

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

接下来创建一个models文件夹。将此架构保留在此模型文件夹中。我把它命名为product.js。这是代码

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);

接下来创建一个routes文件夹,并将此路由代码保留在此文件夹中,我将其命名为route.js。这是代码

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;

下一个服务器代码我将其命名为app.js。这是代码

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");
});

node app.js运行服务器。

<强> API的

  1. 使用GET方法http://localhost:3000/route/product。这是为了获取所有产品信息。

  2. 使用POST方法http://localhost:3000/route/productData。这可用于创建文档。通过请求体(如

    )以json格式发布数据

    {

    “productName”:“甜点”, “productPrice”:“33”

    }

  3. 您会看到这样的回复。

    enter image description here 首先发布一些文档,即发布2或3个文档,然后您可以看到上面提到的get API文档。然后你会看到所有文件都包含空子文件。你会看到像这样的回复

    enter image description here

    现在使用下面的api将子文档添加到所有文档。

    1. 使用POST方法http://localhost:3000/route/subdocument。使用此方法,您可以将子文档添加到所有文档中,例如,您需要添加子文档

      {

      “imagepath”:“桌面”

      }

    2. 您可以看到这样的回复

      enter image description here

      再次运行get API后,您可以看到所有子文档都已添加到所有文档中。

      enter image description here

      希望这有帮助。