在将数据发布到mongoDb之后如何获取id?

时间:2017-08-30 06:06:31

标签: angularjs node.js mongodb express

我正在使用node.js,angularjs,& MongoDB的。
我正在创建一个产品上传页面。

它分为两部分:

  1. 数据页:此部分将包含textfields&下拉列表。
  2. 图片上传页面:此部分将进行图片上传控制。
  3. 所以我想在同一页面中创建2个表单,从第一页开始我将文本数据发布到mongoDb,返回新创建的产品的 product_id ,然后上传带有 product_id的图像即可。

    我开发了restFul API来发布产品api/products/create-product
    产品型号

    {
    productName:{type: String},
    productPrice:{type: Number}
    }
    


    图片模型

    {
    productId:{type: String},
    imagePaths:[{type: Array}]
    }
    


    产品总监(Angular):

    $scope.newProduct = function(){
          var formData = new FormData;
          for(key in $scope.product){
            formData.append(key, $scope.product[key]);
          } 
      //getting the files
      var file = $('#file')[0].files[0];
      formData.append('image', file);
    
      //Post data
      $http.post('http://localhost:3000/products/api/new-product',formData,{
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
      }).then(function(res){
        $scope.item = res.data;
    
      });
    }
    


    Angular front-end

    <input type="text" class="form-control" ng-model="product.productName" placeholder="Enter Product Name">
    <input type="file" multiple="multiple" id="file" >
    <button type="submit" ng-click="newProduct()" class="btn btn-primary">Add Product</button>
    


    POST API

    router.post('/api/new-product',upload.any(),function(req, res, next){
    
      var pro = req.body;
      if(req.files){
        req.files.forEach(function(file){
    
          var filename = (new Date()).valueOf() + '-' + file.originalname;
          fs.rename(file.path,'public/images/'+ filename, function(err){
            if (err) throw err;
            //Save to mongoose
    
          var product = new Products({
              productName: req.body.productName
             });
              product.save(function(err, result){
              if(err){ throw err}
                res.json(result);
            });
    
    
    
          });
        });
      }
    });
    

    问题

    1. 我这样做是否正确,还是有另一种更好的方法呢?
    2. 如果这是正确的方法,那么我如何发布 product_id 发布图片?
      感谢。

3 个答案:

答案 0 :(得分:1)

这是我的配置文件,它与mongodb建立连接。这是config.js

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

这是我的schema's。我创建了两个集合,一个是products,另一个是images。将这两个模式保存在models文件夹中。这是我的产品架构,我将其命名为product.js

var mongoose = require('mongoose');

var nameSchema = new mongoose.Schema({

productName:{type: String},
productPrice:{type: Number}

});
module.exports  = mongoose.model("product", nameSchema);

这是我的图片架构,我将其命名为image.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imageSchema = new Schema({
imagepath:{
    type:String,
    required:true
}
});
var nameSchema = new Schema({
 productId:{type: String},
imagePaths:[imageSchema]
});
module.exports  = mongoose.model("image", nameSchema);

这是html文件将此文件保存在views文件夹中。我把它命名为index.html

<form id="uploadForm"
      enctype="multipart/form-data"
      action="/api/file"
      method="post"
>
 <input type="file" name="userFile"/>
<input type="submit" value="Upload File" name="submit">

</form>

接下来是路由文件将此文件保存在routes文件夹中,并将其命名为route.js

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

var Image = require('../models/image');
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.put('/postingImage/:Id',function(req,res,next){
 Image.findByIdAndUpdate(req.params.Id, {
        $set: req.body
    }, {
        new: true
    }, function (err, batch) {
        if (err) throw err;
        res.json(batch);
    });
})

Router.get('/image',function(req,res){
 Image.find({}, function (err, img) {
        if (err) throw err;
        res.json(img);
    });
})  
    module.exports = Router;

以下是将其命名为app.js

的服务器代码
var express = require('express');
var multer = require('multer');
var bodyParser = require('body-parser');
var Image = require('./models/image');
var Product = require('./models/product');
var mongoose = require('mongoose');
var path = require('path');
var rand;
var urlencodedParser = bodyParser.urlencoded({ extended: false });

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 ejs = require('ejs')
app.set('view engine', 'ejs')
var storage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './public/uploads')
    },
    filename: function(req, file, callback) {
        //callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
                //callback(null, file.originalname)
        rand=Date.now() + path.extname(file.originalname);

        callback(null, file.fieldname + '-' + rand);

    }

})
var upload = multer({
        storage: storage});
app.get('/api/file',function(req,res){
res.sendFile('E:/syed ayesha/nodejs/nodejs/uploads/db/views/index.html');
});

app.post('/api/file',upload.single('userFile'), function(req, res) {
    console.log(req.file);
    console.log(req.file.path);

    Image.create({imagePaths:[{imagepath:req.file.path}]},function(err,img){

            if (err) throw err;
     console.log(img);
        console.log('Path created!');
        var id = img._id;

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

var route = require('./routes/route');
app.use('/route',route);
    app.listen(3000,function(){
    console.log("Server listening on 3000");
});

node app.js

运行服务器

以下是我API's发布产品详情&amp;在mongodb中发布图像路径

  1. 使用POST方法发布产品详情,请使用http://localhost:3000/route/productData。通过正文发布数据
  2. {     “产品名称”:“霜”,     “productPrice”:88 }

    1. 使用GET方法从mongodb获取该产品的detials http://localhost:3000/route/product

    2. 现在打开浏览器并输入http://localhost:3000/api/file然后选择要上传的文件点击提交按钮然后您将获得文档ID作为回应。只需记下此ID。您将使用此我发布imageI中的productId。

    3. 如果您想使用GET方法查看mongodb中的图片路径详情,请使用http://localhost:3000/route/image

    4. 现在,您可以使用之前获得的文档ID在图像架构中添加productId。为此使用PUT方法并在此使用http://localhost:3000/route/postingImage/59ae2f9195730f1e00be7509,我只是将文档ID提供给您。您需要将文档ID放在那里。并像这样通过正文发送productId

      {     “的productId”: “59a6ac68a87d9f102c4496b8” }

    5. 在此之后,您将回复enter image description here

      你也可以参加mongodb。

      1. use image
      2. show collections
      3. db.images.find().pretty();
      4. db.product.find().pretty(); 希望这会有所帮助。

答案 1 :(得分:0)

5秒进入谷歌(没有测试):

collection.insert(objectToInsert, function(err){
   if (err) return;

   // Object inserted successfully.
   var objectId = objectToInsert._id; // this will return the id of object inserted
});

Source

答案 2 :(得分:0)

您可以使用此代码发布产品数据

app.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);
    });    
})

以同样的方式,您可以使用product_id发布图像,该产品将在mongodb中添加产品时作为响应。当您想要查看它所属的图像时,您可以将product_id作为参数传递

app.get('/productImage/:productId',function(req,res,next){
Image.find({"product_id":req.params.productId}, function (err, data) {
    if(err) console.log("error");
    if(data==true){
        res.json(batch);
    }
    });
});

如果您需要任何其他信息,请告知我们。希望这有帮助