带有Nodejs的Json Array对象mongodb中的插入问题?

时间:2017-10-09 11:53:23

标签: json node.js mongodb

我是mongodb的新手,我在mongodb中有Json结构,

{
    "_id" : ObjectId("59d62452a164b51d64b714c2"),
    "folderName" : "Avinash 1234",
    "tag" : "search",
    "ismainFolder" : true,
    "innerFolder" : [ 
        {
            "ismainFolder" : false,
            "foldername" : "Test12",
            "_id" : ObjectId("59d72246e66adf2cfcfdd6e6")
        }
    ],
    "innerFiles" : [ 
        {
            "filelocation" : "",
            "isFolder" : false,
            "filename" : "Penguins.jpg",
            "_id" : ObjectId("59d7223de66adf2cfcfdd6e5")
        }, 
        {
            "filelocation" : "",
            "isFolder" : false,
            "filename" : "Desert.jpg",
            "_id" : ObjectId("59d72ff4e66adf2cfcfdd6ec")
        }, 
        {
            "filelocation" : "",
            "isFolder" : false,
            "filename" : "Hydrangeas.jpg",
            "_id" : ObjectId("59d731dfe66adf2cfcfdd6ed")
        }, 
        {
            "filelocation" : "",
            "isFolder" : false,
            "filename" : "Chrysanthemum.jpg",
            "_id" : ObjectId("59d73252e66adf2cfcfdd6ee")
        }

    ],
    "__v" : 0
}

对于innerFiles数组,我需要根据id插入Tag字段(“_ id”:ObjectId(“59d7223de66adf2cfcfdd6e5”))。我使用了以下nodeJs代码,但它添加为新对象。请给我解决方案。

exports.addTagForSearch = function (req, res, next) {
    var tagDetails = req.body.tagDetails;
    console.log("tagDetails", tagDetails);
    console.log("tagDetails", tagDetails._id);
    Repository.find({ _id: tagDetails._id, }, { innerFiles: { $elemMatch: { _id: tagDetails._id } } },function (err, response) {
        $push: {
                innerFiles: {
                    "tagName": tagDetails.tagname,
                    }
            //"filelocation": tagDetails.filelocation
        }

    }, { upsert: true, new: true }, function (err, post) {
        if (err) return next(err);
        return res.status(200).json("success");
    });
}

但是作为新对象插入代码,请给我解决方案。

1 个答案:

答案 0 :(得分:1)

首先,我需要为我创建一个config.js文件的数据库。这是代码

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

接下来创建一个models文件夹,并将此order.js保留在其中

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var folderSchema=new Schema({

    ismainFolder:{
        type:String,
        //required:true,
        default:''
    },
foldername:{
        type:String,
        //required:true,
        default:''
    }

});

var innerSchema=new Schema({

    filelocation:{
        type:String,
        //required:true,
        default:''
    },
    isFolder:{
        type:String,
        //required:true,
        default:''
    },
    filename:{
        type:String,
        //required:true,
        default:''
    }

});

var main= new Schema({
folderName:{type:String},
tag:{type:String},
ismainFolder:{type:String},
    innerFolder:[folderSchema],
    innerFiles:[innerSchema]

},{ strict: false });



var Order= mongoose.model('main', main);

// make this available to our Node applications
module.exports = Order;

接下来创建一个routes文件夹并将此orderRouter.js文件保留在其中

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

var Orders = require('../models/orders');
var app = express();

var orderRouter = express.Router();
orderRouter.use(bodyParser.json());

orderRouter.get('/get',function (req, res, next) {
    Orders.find({}, function (err, order) {
        if (err) throw err;
        res.json(order);
    });
})

orderRouter.post('/post',function (req, res, next) {
   Orders.create(req.body, function (err, order) {
        if (err) {
            res.status(400).send('Bad request');
        }
        else{
        console.log('order created!');
        var id = order._id;

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

orderRouter.get('/:orderId',function (req, res, next) {
    Orders.findById(req.params.orderId, function (err, order) {
        if (err) {
            res.status(404).send('OrderId not found');
        }
        else{
        res.json(order);
        }
    });
})

orderRouter.put('/addingField',function(req,res){
             //var tagDetails = req.body;
             console.log("tagDetails:"+req.body.subId);
             console.log("tagname:"+req.body.tagname);
Orders.update(
{_id:req.body.mainId,'innerFiles._id':req.body.subId},
{$set:{'innerFiles.$.tagName':req.body.tagname}},
function (err, article) {
  if (err) return console.log(err);
  res.json(article);
});
});

app.use('/orders',orderRouter);
app.use(express.static(__dirname+'/public'));
module.exports = orderRouter;

接下来创建一个app.js文件,这是服务器代码

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

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 () {
    // we're connected!
    console.log("Connected correctly to server");
});
var orderRouter = require('./routes/orderRouter');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// passport config

app.use(passport.initialize());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/orders',orderRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.json({
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.json({
    message: err.message,
    error: {}
  });
});
app.listen(3000,function(){
console.log("Server listening on 3000");
});
module.exports = app;

node app.js运行服务器。您可以使用此post http://localhost:3000/orders/post post数据来使用{ "folderName" : "Avinash 1234", "tag" : "search", "ismainFolder" : "true", "innerFolder" : [ { "ismainFolder" : "false", "foldername" : "Test12" } ], "innerFiles" : [ { "filelocation" : "a", "isFolder" : "false", "filename" : "Penguins.jpg" }, { "filelocation" : "b", "isFolder" : "false", "filename" : "Desert.jpg" }, { "filelocation" : "c", "isFolder" : "false", "filename" : "Hydrangeas.jpg" }, { "filelocation" : "d", "isFolder" : "false", "filename" : "Chrysanthemum.jpg" } ] } 方法。这是发布的示例输入示例< / p>

mainId

这里是它的图像

enter image description here

发布数据后检查您的数据是否存储在数据库中。这里我提供的ID是http://localhost:3000/orders/get。对于该运行,此api get使用subId方法。在我们的代码中收集http://localhost:3000/orders/addingField的子文档ID。获取

的示例图像

enter image description here

此后是为子文档添加新字段的任务,使用此api put,您需要使用{ "mainId":"59dca6aff968a98478aaaa96", "subId":"59dca6aff968a98478aaaa9a", "tagname":"hello" } 方法。这是输入示例

INSTR

和它的形象

enter image description here

完成所有这些步骤后,请检查db.Here是否为示例图像 它 enter image description here

就是这样。希望它有所帮助。