我是Node JS的新手,我试图用Mongoose从Mongo数据库中获取用户,但这给了我错误。这是我在db.js
中的UserScheme:
const config = require('config');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.connect(config.get('mongo.uri'));
mongoose.set('debug', config.get('app.verbose') === true);
mongoose.set('useFindAndModify', false);
const UserSchema = new Schema({
phone : String,
shortPhone : String,
password : String,
averageRating : Number,
profile : {
email : String,
mainlyHereFor: String,
enabledVideoResume: {type: Boolean, default: false},
seekingOpportunityType: String,
fullName : String,
username : String,
address : {
city : {type: String, default: 'Unknown'},
state : String,
country: String,
zip : String
},
}
}
exports.User = mongoose.model('User', UserSchema);
正在创建用户,但是当我尝试通过ID与猫鼬找到用户时,它给了我一些invalid type
错误:
const express = require('express');
const db = require('../db');
router.get('/search', (req, res) => {
db.User.findById('5f20ec88d5cf2f2994bc42d4') // req.user.id)
.then((user) => {
let connsFilter = user.connections.filter((conn) => conn.relationship == 'connected');
const users = connsFilter.map((conn) => conn.user);
let query = {
'connections.user': { $in: users }
};
return db.User.find(query)
.select('-contacts')
.populate({ path: 'jobs', match: { spam: false } });
})
.then((result) => {
res.json(result);
})
.catch((err) => {
res.status(400).json({ status: 'bad', error: err });
});
});
单击db.User总是将我带到User模式的定义,但是即使该用户存在于我的数据库中,它仍然转到catch块。
答案 0 :(得分:0)
使用 db.User.findById(ObjectId('5f20ec88d5cf2f2994bc42d4')), 如果ur _id是object_id而不是普通字符串,则必须使用ObjectId