Tom Vos
Tom Vos

Reputation: 29

Mongoose not finding documents that weren't created with mongoose

I have created a collection and a document in a local running db using mongosh, and want to access it via mongoose. However, when I query all documents using a model that is exactly the same as the collection I created, it doesn't find the document.

user.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, where I do the query(not the full file, only the bits necesarry)

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);
}
})

Database in Compass:

NOTE: I tried it with a connection with the db in admin.js(not in my latest attempt that I showed), but it didn't work... I looked up how to access documents from the db, and even the mongoose docs said this was how to do it.

Anyone who can help?

Upvotes: 1

Views: 1049

Answers (1)

barrypicker
barrypicker

Reputation: 10088

So I created the following test...

app.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;

If I run it the first time I have no data, it creates a record and shows it...

Invoke App

node app.js

Output

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

And if I manually insert a record into the database using mongoshell...

Manually Created Database Record

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

... and run the program a second time, I get 3 records, two the program created plus the one manually created.

%> 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
  }
]

It seems to work correctly as far as I can tell. The manually created record does not have a __v column but it shows in the output....

Upvotes: 1

Related Questions