Problem: I was trying to get my head around on population in mongoose.js, I got this error out of nowhere when I tried to populate the 'user' field of a post document.
PS: This is complete code except for the connection string part, so you can try and see what went wrong. Thanks in advance!!!
const express = require('express');
const mongoose = require('mongoose');
//set up the server
const app = express();
app.listen(3000);
console.log("Server listening to port 3000");
//set up the mongosoe connection
mongoose.connect("YOUR MONGODB URI", {
useCreateIndex : true,
useNewUrlParser : true,
useUnifiedTopology : true,
}).then(() => {
console.log("Connection established");
}).catch(err => {
throw err;
});
//set up the models
const User = mongoose.model('user', new mongoose.Schema({
name : String,
}));
const Post = mongoose.model('post', new mongoose.Schema({
user : {
type : mongoose.Schema.Types.ObjectId,
ref : 'User',
},
content : String,
}));
//create a User and Post
new User({
name : "Nike",
}).save((err, user) => {
console.log("The user was saved");
new Post({
user : user._id,
content : "I laugh a lot",
}).save(() => {
console.log("The post is saved");
});
});
//populate the post with user
(async function() {
try {
let post = await Post.findOne({}).populate('user');
console.log(post);
} catch (err) {
throw err;
}
})();
Error
(node:41792) UnhandledPromiseRejectionWarning: MissingSchemaError: Schema hasn't been registered for model "User".
Use mongoose.model(name, schema)
at NativeConnection.Connection.model (C:\Users\Nikesh K Lepcha\Documents\node_modules\mongoose\lib\connection.js:1192:11)
at getModelsMapForPopulate (C:\Users\Nikesh K Lepcha\Documents\node_modules\mongoose\lib\helpers\populate\getModelsMapForPopulate.js:285:59)
at populate (C:\Users\Nikesh K Lepcha\Documents\node_modules\mongoose\lib\model.js:4320:21)
at _populate (C:\Users\Nikesh K Lepcha\Documents\node_modules\mongoose\lib\model.js:4290:5)
at C:\Users\Nikesh K Lepcha\Documents\node_modules\mongoose\lib\model.js:4266:5
at promiseOrCallback (C:\Users\Nikesh K Lepcha\Documents\node_modules\mongoose\lib\helpers\promiseOrCallback.js:9:12)
at Function.Model.populate (C:\Users\Nikesh K Lepcha\Documents\node_modules\mongoose\lib\model.js:4264:10)
at model.Query.Query._completeOne (C:\Users\Nikesh K Lepcha\Documents\node_modules\mongoose\lib\query.js:2109:9)
at Immediate.<anonymous> (C:\Users\Nikesh K Lepcha\Documents\node_modules\mongoose\lib\query.js:2148:10)
at Immediate.<anonymous> (C:\Users\Nikesh K Lepcha\Documents\node_modules\mquery\lib\utils.js:116:16)
at processImmediate (internal/timers.js:456:21)
You registered user
but reference it as User
. Look at the difference:
mongoose.model('user'
and
ref : 'User'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.