无法使用mongoose使用node.js连接到mongoDB

时间:2019-09-24 07:33:28

标签: node.js mongodb mongoose

这是我编写的代码:

const mongoose = require('mongoose')
const userSchema = require('./userSchema.js')
const User = mongoose.model('user', userSchema, 'user')

async function createUser(username) {
    return new User({
        username,
        created: Date.now()
    }).save()
}

async function findUser(username) {
    return await User.findOne({
        username
    })
}

;
(async() => {
    const connector = mongoose.connect(connectionString)
    const username = process.argv[2].split('=')[1]

    let user = await connector.then(async() => {
        return findUser(username)
    }).catch(console.log("Error found"))

    if (!user) {
        user = await createUser(username)
    }

    console.log(user)
    process.exit(0)
})()

但是出现以下错误。我不知道出了什么问题。任何想法?

code error snippet here

3 个答案:

答案 0 :(得分:0)

尝试此命令

sudo service mongod start

然后nodemonnode app.js启动服务器。

答案 1 :(得分:0)

请检查您的连接字符串。您可以从Mongo地图集获取连接字符串。

  1. https://developerhandbook.com/mongodb/connect-mongo-atlas-mongoose/

答案 2 :(得分:0)

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();


// Connecting to the database
mongoose.connect('mongodb:uri',{ useNewUrlParser: true } ).then(() => {
    console.log("Successfully connected to the database");
}).catch(err => {
    console.log('Could not connect to the database. Exiting now...');
    process.exit();
});