Javascript 如何将数据插入mongodb
我正在尝试使用nodeJS向端口27017托管的mongodb blogdb插入一条记录 我一直在图像中看到错误。我得到的错误是“localhost:27017套接字已关闭” 我试图输入的记录是Javascript 如何将数据插入mongodb,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我正在尝试使用nodeJS向端口27017托管的mongodb blogdb插入一条记录 我一直在图像中看到错误。我得到的错误是“localhost:27017套接字已关闭” 我试图输入的记录是 var post1 = { title:"Flight 2012", by:"posiden", tags:["planes","movies","pilot"], likes:86, }; 这是我的db.js文件,我已将其作为node db.js执行 [![//req
var post1 = {
title:"Flight 2012",
by:"posiden",
tags:["planes","movies","pilot"],
likes:86,
};
这是我的db.js文件,我已将其作为node db.js执行
[![//require mongodb native drivers
var mongodb = require('mongodb');
//getting the mongo client interface to connect witha mongodb server
var MongoClient = mongodb.MongoClient;
//connection url of the database
var url = 'mongodb://localhost:27017/blogdb';
//use the connect method to conenct to the server
MongoClient.connect(url,function(err,db){
if(err){
console.log("Unabel to connect to mongo server ERROR : " ,err);
}else {
console.log("Connection sucesful to ", url);
var collection = db.collection('posts');
var post1 = {
title: "Flight 2012",
by: "posiden",
tags: \["planes", "movies", "pilot"\],
likes: 86,
};
collection.insert(\[post1\], function (err, result) {
if (err) {
console.log("ERROR ", err);
}
else {
console.log("SUCCESS INSERTED in to users collection _is are ", result.length, result)
}
});
}]
首先,您的JSON不正确。JSON中最后一个元素(在您的例子中是“likes:86”)后面不应该有逗号(“,”)。以下是正确的JSON:
var post1 = {
title:"Flight 2012",
by:"posiden",
tags:["planes","movies","pilot"],
likes:86
};
请稍后再试。如果您仍然遇到问题,请报告。此处的“退出”斜杠是什么?如果你把所有的
\`
都拿出来,那么一切都没问题。当然还有结尾的[1][1]
。这是关于什么的?你能解释一下你的最后一行][1][1]
和\[post1\]
?首先,你能用命令“mongod”检查mongo是否正在运行吗?套接字关闭错误表明无法访问数据库。您能否验证数据库是否正在运行,如果正在运行,您是否在基于Windows的计算机上?您可能会遇到Mongo被锁定的问题。