所以我创建了以下测试......
应用程序.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 列,但它显示在输出中......