1

我已经使用 mongosh 在本地运行的数据库中创建了一个集合和一个文档,并希望通过 mongoose 访问它。但是,当我使用与我创建的集合完全相同的模型查询所有文档时,它找不到文档。

用户.js:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/zenwheels', {useNewUrlParser:true, 
useUnifiedTopology: true});


const userSchema = new mongoose.Schema({

username:{
    type: String,
    required: true
},
    password:{
    type: String,
    required: true
}

});

module.exports = mongoose.model('user', userSchema);

admin.js,我在其中进行查询(不是完整文件,只有必要的位)

const user = require('../models/user');

router.get('/gettest/', async (req, res) =>{

try{
    const users = await user.find();
    res.json(users);
}catch(err){
    res.send(500);
}
})

Compass 中的数据库:

注意:我在 admin.js 中尝试了与 db 的连接(不是在我展示的最新尝试中),但它不起作用......我查找了如何从 db 甚至是猫鼬访问文档文档说这是怎么做的。

有谁能帮忙吗?

4

1 回答 1

1

所以我创建了以下测试......

应用程序.js

const mongoose = require("mongoose");
const user = require("./models/user");

run().catch(error => console.log(error));

async function run() {
    var uri = "mongodb://barry:barry@localhost:50011,localhost:50012,localhost:50013/nodetest?replicaSet=replSet&authSource=admin";
    const connectionOptions = { useNewUrlParser: true, useUnifiedTopology: true };
    await mongoose.connect(uri, connectionOptions);
    
    await user.create({username: "testuser", password: "testpassword" });
    await getUsers();
}

async function getUsers() {
    try {
        const users = await user.find();
        console.log(users);
    }
    catch (err) {
        console.log(err);
    }
}

./models/user.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema(
    {
        username: { type: String, required: true },
        password: { type: String, required: true }
    },
    {
        collection: "user"
    }
);

const user = mongoose.model('user', userSchema);
module.exports = user;

如果我第一次没有数据时运行它,它会创建一条记录并显示它......

调用应用程序

node app.js

输出

[
  {
    _id: new ObjectId("612598d93d79a5db726a348d"),
    username: 'testuser',
    password: 'testpassword',
    __v: 0
  }
]

如果我使用 mongoshell 手动将记录插入数据库......

手动创建的数据库记录

Enterprise replSet [primary] nodetest> db.user.insert({username : "manuallycreated", password: "somevalue"})
{
  acknowledged: true,
  insertedIds: { '0': ObjectId("612598ff5e46191be26454b0") }
}

...并再次运行该程序,我得到 3 条记录,两条是创建的程序加上一条手动创建的。

%> node app.js
[
  {
    _id: new ObjectId("612598d93d79a5db726a348d"),
    username: 'testuser',
    password: 'testpassword',
    __v: 0
  },
  {
    _id: new ObjectId("612598ff5e46191be26454b0"),
    username: 'manuallycreated',
    password: 'somevalue'
  },
  {
    _id: new ObjectId("61259932f79fa93d54bd8acb"),
    username: 'testuser',
    password: 'testpassword',
    __v: 0
  }
]

据我所知,它似乎工作正常。手动创建的记录没有 __v 列,但它显示在输出中......

于 2021-08-25T01:14:50.973 回答