最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I use .populate with .findOne in an Express route? - Stack Overflow

programmeradmin4浏览0评论

I'm in the process of learning Node, Mongoose and Express by trying to build a CRUD API. When trying to "join" two MongoDB collections with the .populate function, I get an error that

db.collection(...).findOne(...).populate is not a function

My javascript chops are not great, so I've tried rewriting this in different ways to no avail.

server.js

require('./models/User')
require('./models/Product')

var db 

mongodb.MongoClient.connect('mongodb://<username>:</password>@xxxx.mlab:xxx/xxx', (err, database) => {
if (err) return console.log(err)
    db = database
    app.listen(3000, function() {
        console.log("listening on port 3000");
    })
})

app.get('/api/users/:id', (req, res) => {
db.collection(USERS_COLLECTION).findOne({ id: (req.params.id) }).populate('product'), (err, doc) => {
    if (err) handleError(res, err.message, 'Failed to get user')

    res.status(200).json(doc)   
    console.log(req.params)
 }
})

models/user.js

 var mongoose = require('mongoose')

 var UserSchema = new mongoose.Schema({
 id: String,
 first_name: String,
 last_name: String
 id: {
 type: mongoose.Schema.Types.ObjectId,
 ref: 'Product'
 }
})

mongoose.model('User', UserSchema)

I'm in the process of learning Node, Mongoose and Express by trying to build a CRUD API. When trying to "join" two MongoDB collections with the .populate function, I get an error that

db.collection(...).findOne(...).populate is not a function

My javascript chops are not great, so I've tried rewriting this in different ways to no avail.

server.js

require('./models/User')
require('./models/Product')

var db 

mongodb.MongoClient.connect('mongodb://<username>:</password>@xxxx.mlab.:xxx/xxx', (err, database) => {
if (err) return console.log(err)
    db = database
    app.listen(3000, function() {
        console.log("listening on port 3000");
    })
})

app.get('/api/users/:id', (req, res) => {
db.collection(USERS_COLLECTION).findOne({ id: (req.params.id) }).populate('product'), (err, doc) => {
    if (err) handleError(res, err.message, 'Failed to get user')

    res.status(200).json(doc)   
    console.log(req.params)
 }
})

models/user.js

 var mongoose = require('mongoose')

 var UserSchema = new mongoose.Schema({
 id: String,
 first_name: String,
 last_name: String
 id: {
 type: mongoose.Schema.Types.ObjectId,
 ref: 'Product'
 }
})

mongoose.model('User', UserSchema)
Share Improve this question edited Feb 20, 2017 at 19:51 Bardo_J asked Feb 20, 2017 at 19:21 Bardo_JBardo_J 511 gold badge1 silver badge7 bronze badges 3
  • Which node module is db? – Sangharsh Commented Feb 20, 2017 at 19:22
  • If you are using Mongoose then you can use schema methods so you should be able to use .populate on a model object – Explosion Pills Commented Feb 20, 2017 at 19:26
  • @Sangharsh I've added how i'm setting up the db to the top of the code – Bardo_J Commented Feb 20, 2017 at 19:29
Add a ment  | 

1 Answer 1

Reset to default 2

Collections don't have the mongoose's model API including .populate. Instead of using collections directly, you should use the model that you registered in mongoose.

var schema = new mongoose.Schema(...);

var User = mongoose.model('User', schema);
// you can also get the model after it was registered via mongoose.model('User')

app.get('/api/users/:id', (req, res) => {
User.findOne({ id: (req.params.id) }).populate('product'), (err, doc) => {
    if (err) handleError(res, err.message, 'Failed to get user')

    res.status(200).json(doc)   
    console.log(req.params)
 }
})

发布评论

评论列表(0)

  1. 暂无评论