简体   繁体   中英

Configuring mongodb and inserting a JSON

Background: I am a beginner in both Node.js and Mongodb. I'v been following a tutorial to just setup mongodb with node.js locally to practice inserting/deleting.

What i am trying to accomplish: I just want to be able to create a db, insert the following 'object' and print it out from db to confirm it worked.

What i have tried

var url = "TheDatabase";
var collections = ["Location"];
var mongojs = require("mongojs")
var db = mongojs(url, collections);

var object = {
    "place" : {
        "address" : "123 road",
        "code" : "ABC CDE",
        "letters" : "AA",
        "coord" : [  99.55, -20.5 ]
    },
    "keyword1" : "World",
    "keyword2" : "Biomech",
    "keyword3" : "Spotify",
    "_id" : "1"
}

db.collection.save(doc);

So i learned about mongojs, and followed a tutorial here. http://howtonode.org/node-js-and-mongodb-getting-started-with-mongojs

var db = require("mongojs").connect(databaseUrl, collections);

This line didnt work for me in the tutorial so i replaced it with the following

var mongojs = require("mongojs")
var db = mongojs(url, collections); 

then i discovered Collection.save() and thought that might work to save the object?

Edit

So i have discovered db.Location.save(object) but now i receive this error

C:\Users\user\Desktop\..\node_modules\mongodb\lib\server.js:236
        process.nextTick(function() { throw err; })
                                      ^
 Error: connect ECONNREFUSED 127.0.0.1:27017
    at Object.exports._errnoException (util.js:870:11)
    at exports._exceptionWithHostPort (util.js:893:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)

您需要在集合名称上调用save方法。

db.Location.save(object)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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