我有这样的模特和系列。
user.js的
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
email: String, //convert to contacts with type Object
username: String,
password: String,
createdAt: {
type: Date,
default: Date.now
},
updatedAt: {
type: Date,
default: Date.now
}
});
const User = mongoose.model('user', UserSchema);
module.exports = User;
服务器集合
{
"_id" : ObjectId("591d3736e562d87e5f7a4435"),
"name" : "test.snapzio.com",
"description" : "test",
"hostname" : "hostname",
"ipaddress" : "192.168.1.1",
"status" : "good",
"updatedAt" : ISODate("2017-05-18T05:55:02.920+0000"),
"createdAt" : ISODate("2017-05-18T05:55:02.920+0000"),
"users" : [
{
"id" : "591d2fc1f484ce774c1ca58d",
},
{
"id" : "591d2fc1f484ce774c1ca58d",
},
{
"id" : "591d2fdbf484ce774c1ca58e",
}
],
"projects" : [
ObjectId("591d3079f484ce774c1ca590")
],
"__v" : NumberInt(0)
}
我希望获得与服务器文档中的记录匹配的用户然后呈现。这就是我所做的
router.get('/add_project/:id', ensureAuthenticated, (req, res, next) => {
Server.findById(req.params.id, (err, server) => {
User.find({ _id: server.users.id }, (err, users) => {
console.log(users);//undefined
});
});
});
我希望获得与服务器文档中的记录匹配的所有用户。请考虑不要更改架构。
答案 0 :(得分:0)
这应该有效:
router.get('/add_project/:id', ensureAuthenticated, (req, res, next) => {
Server.findById(req.params.id, (err, server) => {
let server_users = server.users.map(e => e.id);
User.find({ { _id : { $in : server_users } } }, (err, users) => {
console.log(users);
});
});