繁体   English   中英

如何将对象数组插入Mongodb node.js

[英]How do you insert an array of object into Mongodb node.js

基本上,我想将一个名为“事件”的对象数组插入到名为“事件”的Mongodb集合中,并为该数组的每个条目添加一个ID。

这是我想在json中得到的结果:

{
    "events" : [
        {
            "_id" : ObjectId("53a99cc608ad49712a830081"),
            "eTitle" : "Freshers Fair",
            "eDesc" : "Bring some friends with you oh wait, you have non ha !",
            "eDate" : "2014-06-19 11:20",
            "eLink" : "http://fair.com",
            "eEvent" : "NEFS"
        },

        {
            "_id" : ObjectId("53a99cc608ad49712a830082"),
            "eTitle" : "Blahh",
            "eDesc" : "Blah fdinidf !",
            "eDate" : "2014-06-19 11:20",
            "eLink" : "http://google.com",
            "eEvent" : "NEFS"
        }
    ]
}

到目前为止,这是我得到的结果:

[
 { 
   "_id":"53a9b5ed745363432d823d7a",
   "eTitle":"jrnfdeiujn rd",
   "eDesc":"grfdsreds",
   "eDate":"2014-07-05 22:33",
   "eLink":"reser",
   "eEvent":"Victoria Center"
 },
 { 
   "_id":"53a9b771745363432d823d7b",
   "eTitle":"Hello worlds",
   "eDesc":"blah",
   "eDate":"2014-07-20 22:33",
   "eLink":"http://google.com",
   "eEvent":"social"
 }
]

这就是我使用node.js插入数据的方式:

// Set our collection
    var collection = db.get('Events');

    // Submit to the DB
    collection.insert({
        "eTitle" : eTitle,
        "eDesc" : eDesc,
        "eDate" : eDate,
        "eLink" : eLink,
        "eEvent" : eEvent
    }, function (err, doc) {
        if (err) {
            // If it failed, return error
            res.send("There was a problem adding the information to the database.");
        }
        else {
            // If it worked, set the header so the address bar doesn't still say /adduser
            res.location("eventlist");
            // And forward to success page
            res.redirect("eventlist");
        }
    });

所以请我如何使该格式看起来像我提供的第一个json格式。 抱歉nooby问题,刚刚开始学习节点! 非常感谢

更新

要发布活动:

router.get('/eventlist', function(req, res) {
var db = req.db;
var collection = db.get('Events');
collection.find({},{},function(e,docs){
    console.log(docs);
    res.send(docs);
   // res.render('eventlist', {docs: JSON.stringify(docs), title: 'Test'});
}); 

});

你可以这样做:

collection.find({},{},function(e,docs){
    var doc = { Events : docs };
    console.log(doc);
    res.send(doc);
    // res.render('eventlist', {docs: JSON.stringify(docs), title: 'Test'});
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM