如何使用Node js在Mongodb中创建数据库?

时间:2017-10-21 09:30:09

标签: node.js mongodb

Iam初学者,首先我安装了npm install mongodb,然后我创建了js文件作为demo_create_mongo_db.js

我使用以下代码创建数据库

$data = "21//10//2017";

然后我只是在发生错误后运行节点demo_create_mongo_db.js

this error found

为什么会出现此错误?我怎么处理这个?

由于

3 个答案:

答案 0 :(得分:0)

似乎你的mongo服务器还没有运行!! 在注释行中运行mongo以检查mongo服务器是否正在运行。

答案 1 :(得分:0)

  

index.js

首先,通过运行此命令安装MongoDB模块。

  

npm install mongodb --save

请记住,您不能创建唯一的数据库。您还必须创建集合以查看新数据库。

import { View, FlatList, Text, TouchableOpacity } from 'react-native'

class Products extends Component {
    constructor(props){
        super(props);
        this.state={
            dataSource: []
        }
    }

    componentDidMount(){
        fetch("http://localhost:8000/index.php")
        .then(response => response.json())
        .then((responseJson) => {
            this.setState({
                dataSource: responseJson
            })
        })
        .catch(error => console.log(error))
    }



    renderItem = (data) =>
        <TouchableOpacity>
            <Text>{data.item.product_name}</Text>
            <Text>{data.item.product_description}</Text>
            <Text>{data.item.product_model}</Text></TouchableOpacity>


        return (
            <View>
                <FlatList
                    data={this.state.dataSource}
                    renderItem={item => this.renderItem(item)}
                    keyExtractor={item => item.id}
                />
            </View>
        )
}

export default Products

现在在终端中通过以下命令运行此索引文件

  

节点index.js

答案 2 :(得分:0)

您可以使用Mongoose库在Node JS中连接到MongoDB

 var mongoose = require('mongoose');
 mongoose.connect('mongodb://localhost:27017/'+db_to_connect,{ useNewUrlParser: true });

 var db = mongoose.connection;
 db.on('error', function(){             
 });
 db.once('open', ()=> {
 });
相关问题