开发者问题收集

Node.JS MongoDB SyntaxError:无效或意外的令牌

2021-07-12
7770

我不明白哪里出了问题。Node v.16.4.2,NPM v7.18.1

const mongoose = require("mongoose");
// const dotenv = require('dotenv')
require('dotenv').config({path:'variables.env'});

mongoose.connect(process.env.MONGODB_URL, { useNewUrlParser: true}, err => {
    if (err){
        console.log(err);
    } else {
        console.log("Connected to database successfully");

    }
})

/* mongoose.js */
const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error'));
db.once('open', ()=>{
  console.log('DB connected');
});

const express = require('express');
const app = express();
app.get('/', (req, res) => {
  Cat.find({}, (err, healings) => {
    if(err) return res.json(err);
    res.json(healings);
  });
});
app.listen(3000, () => {
  console.log('Connect 3000');
});

const userSchema = mongoose.Schema({
    emotion: Number,
    image: String,
    placeName: String,
    grade: Number,
    id: mongoose.Schema.Types.ObjectId,
});
  ​
const Healing = mongoose.model("user", userSchema); // 스키마 등록
var test = new Healing({ emotion: 1111, image: 'test', placeName:'where', grade:5 });
test.save();

//  const Cat = mongoose.model('Kitty', CatSchema);

错误是

/Users/Downloads/test2/mongoose.js:41

SyntaxError:无效或意外的令牌 at Object.compileFunction (node:vm:352:18) at wrapSafe (node:internal/modules/cjs/loader:1025:15) at Module._compile (node:internal/modules/cjs/loader:1059:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1124:10) at Module.load (node:internal/modules/cjs/loader:975:32) at Function.Module._load (node:internal/modules/cjs/loader:816:12) 在 Function.executeUserEntryPoint [作为 runMain] (node:internal/modules/run_main:79:12) 在 node:internal/main/run_main_module:17:47

2个回答

我认为这是一个编码问题。

例如,请参阅: 尝试运行 Node.js 应用程序时如何修复“SyntaxError:无效或意外的令牌”

尝试使用 UTF-8 编码保存源代码文件。

James Young
2021-07-13

错误指出了第 41 行,该行似乎是紧接在

const Healing = ...
之前的空白行>

当我将该行复制/粘贴到 Vim 中时,它显示 <200b> ,这表明该行包含 零宽度空格 (以 UTF-8 正确编码)。

Joe
2021-07-13