使用Node js插入MongoDB [英] Inserting into MongoDB using Node js
问题描述
使用mongojs模块插入Mongo DB会因加密而失败,我有两个功能,setupMongoDB和pushRequestsToMongoDB(它们的作用是不言自明的). 我从网页上收到一个请求,然后将数据解析为JSON.
Inserting into Mongo DB using the mongojs module fails cryptically,I have two functions,setupMongoDB and pushRequestsToMongoDB(what they do is self-explanatory). I get a request from my web-page and parse the data to JSON.
控制台看起来像这样:
created worker: 22987
created worker: 22989
created worker: 22990
created worker: 22991
{ type: 'line',geometry: '`tvtBat~_Wnaoi@_kc~BzlxZbrvdA{fw[`mw}@' }
object
[Error: connection closed]
产生错误的代码如下:
var mongo=require('mongojs');
var collections=['testData'];
var dbURL='localhost:3000/mapData';
var db=mongo.connect(dbURL,collections);
var insert=function(obj)
{
db.testData.save(obj,function(err,obj){
if(err || !obj)
{
console.log(err);
}
else
{
console.log('Data successfully inserted with _id '+obj['_id']);
}
});
};
exports.insert=insert;
这是我使用该功能的方式:
This is how I use the function:
var express=require('express');
var app=express();
var mongo=require('./mongo_try');
app.use(express.bodyParser());
app.post('/map',function(req,res){
var data=req.body;
console.log(data);
console.log(typeof data);
mongo.insert(data);
});
推荐答案
"conn.markers.save"打算做什么我很困惑.这是猫鼬电话吗? Mongodb节点本机没有保存"命令.您是要获取标记"集合,然后插入数据吗?您无需将其分类.
I'm very confused at what "conn.markers.save" intends to do. Is this a mongoose call? Mongodb node native doesn't have a "save" command. Do you mean to get the "markers" collection, and then insert the data? You won't need to stringify it.
您是否正在使用此代码: https://github.com/mafintosh/mongojs ?
Are you using this: https://github.com/mafintosh/mongojs ?
您也不必使该保存命令字符串化.更改此行:
You shouldn't have to stringify that save command either. Change this line:
conn.markers.save(obj,function(err,data){
或者,如果"obj"的内容已经是字符串,请将其更改为:
Or if the contents of "obj" are already a string, change it to:
conn.markers.save(JSON.parse(obj),function(err,data){
这篇关于使用Node js插入MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!