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

时间:2014-06-24 17:42:27

标签: json node.js mongodb express

基本上我想插入我的Mongodb系列,名为" Events"一组名为" Events"每个条目都有一个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格式。对不起那个蠢蠢的问题,刚开始学习节点!非常感谢

更新

发布活动:

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

});

1 个答案:

答案 0 :(得分:2)

你可以这样做:

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