将数据发布到mongoDb后如何获得id?

我正在使用node.js,angularjs和mongoDb。
我正在创build一个产品上传页面。

它分为两部分:

  1. 数据页面 :这部分将包含文本框和下拉菜单。
  2. 图片上传页面 :这个部分会有图片上传控件。

所以我想在同一页面创build2个表单,从第一页我将文本数据发布到mongoDb,返回新创build的产品的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的前端

 <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 ,以发布图像?
    谢谢。

这是我的configuration文件,它与MongoDB进行连接。 这是config.js

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

这是我的schema's 。 我创build了两个集合,一个是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在mongodb中发布产品详细信息和post imagepath

  1. 使用POST方法发布产品详细信息,请使用http://localhost:3000/route/productData 。 像通过身体发布数据

{“productName”:“cream”,“productPrice”:88}

  1. 使用GET方法从http://localhost:3000/route/product使用MongoDB获得产品detials

  2. 现在打开浏览器并inputhttp://localhost:3000/api/file然后select一个file upload点击提交button,然后你会得到文件ID作为回应。只要记下这个ID。你会用这个我发布productId在Image模式中。

  3. 当你想从mongodb中看到图像path的细节时,使用GET方法并使用http://localhost:3000/route/image

  4. 现在,您可以使用之前获得的文档ID在图像模式中添加productId。 对于这个使用PUT方法,并使用http://localhost:3000/route/postingImage/59ae2f9195730f1e00be7509在这里,我只是给了我的文档Id。你需要把你的文档Id在那里。 并像这样通过body发送productId

    {“productId”:“59a6ac68a87d9f102c4496b8”}

在此之后,你会将答复作为 在这里输入图像说明

你也可以用mongodb来切换。

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

5秒到谷歌(没有testing):

 collection.insert(objectToInsert, function(err){ if (err) return; // Object inserted successfully. var objectId = objectToInsert._id; // this will return the id of object inserted }); 

资源

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

 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将作为响应得到。 当你想看到它所属的图像时,你可以传递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); } }); }); 

如果你想要任何其他信息让我知道。 希望这可以帮助