首页 > 解决方案 > 当我使用猫鼬的 populate() 时,集合中的所需字段未显示

问题描述

我正在使用猫鼬的 populate(),但结果省略了该字段。我找不到具有某些价值的填充字段。集合中未使用“ref”的所有其他字段都显示在集合中。

我曾尝试在 Mongo/Mongoose Query Results 的 Missing 字段中找到解决方案,Mongoose 'populate' not populating和其他几个解决方案,但它对我不起作用。

Room 的模型是(在第 4 行,我声明了 ownerId):

1 const mongoose = require('mongoose');
2 const roomSchema = mongoose.Schema({
3    //_id: mongoose.Schema.Types.ObjectId,
4    ownerId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
5    memberIds: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' 
6     }],
7    room_name: { type: String, required: true, unique: true, 
8    default: ""},
9    password: { type: String, required: true, default: ""},
10    timestamp: { type: Date, default: Date.now },
11    });
12 module.exports = mongoose.model('Room', roomSchema, 'Room');

用户的模型是:

1 const mongoose = require('mongoose');
2 const userSchema = mongoose.Schema({
3  _id: mongoose.Schema.Types.ObjectId,
4  email: {
5    type: String,
6    required: true,
7    unique: true,
8    match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=? 
9    ^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?: 
10    [a-z0-9-]*[a-z0-9])?/
11    },
12  user_name: { type: String, required: true, unique: true},
13  display_name: { type: String, require: false,default: ""},
14  password: { type: String, required: true },
15  user_image: { type: String, required: false, default: 
16  "userAvatar/profile.png"},
17  user_coins: { type: Number, default: 0 },
18  user_aboutme: { type: String, default: "" },
19  user_gender: { type: String, default: ""},
20  user_isVIP: { type: Boolean, default: false },
21  user_isVerified: { type: Boolean, default: false },
22  timestamp: { type: Date, default: Date.now },
23  user_isOnline: { type: Boolean, default: false }
24  });
25  module.exports = mongoose.model('User', userSchema, 'User');

在这里,在这个创建房间的代码中,在第 22 行,我使用了 populate

1 const Room = require("../models/room");
2 const User = require("../models/user");
3 exports.room_create = (req, res, next) => {
4   User.find({ email: req.body.email })
5    .exec()
6    .then(user => {
7      console.log(user);
8      if (user.length < 1) {
9        return res.status(409).json({
10        message: "User doesn't exists"
11        });
12      } else {
13          const room = new Room({  
14            room_name: req.body.roomname,
15            password: " "
16          });
17          room
18            .save()
19            .then(result => {
20               console.log("The result is: # " +result);
21               Room.find({ room_name: req.body.roomname })
22                .populate('ownerId')
23                .exec()
24                .then(room => {
25                   console.log("I am here ### Here ###");
26                 })
27               res.status(201).json({
28                 message: "Room created"
29               }); 
30             })
31            .catch(err => {
32               console.log(err);
33               res.status(500).json({
34               error: err
35             });
36         });
37       }
38   });
39 };

这就是它在 app.js 中连接到 mongo 的方式。

mongoose.connect('mongodb://localhost/peopleTalk', {
  //peopleTalk contain collections : ["User", "Room"]
  useCreateIndex: true,
  useNewUrlParser: true
});

mongoose.Promise = global.Promise;

现在,当我向服务器发送请求时,我得到状态码 201 并且没有错误。

但是当我检查 Room 集合时,我发现 ownerId 丢失了。

> db.Room.find().pretty();
{
     "_id" : ObjectId("5c51eaa8bf999c0f339dad04"),
     "memberIds" : [ ],
     "room_name" : "my room",
     "password" : " ",
     "timestamp" : ISODate("2019-01-30T18:19:20.556Z"),
     "__v" : 0
}

我希望输出如下:

> db.Room.find().pretty();
{
    "_id" : ObjectId("5c51eaa8bf999c0f339dad04"),
    "ownerId" : (_here with some value_),
    "memberIds" : [ ],
    "room_name" : "my room",
    "password" : " ",
    "timestamp" : ISODate("2019-01-30T18:19:20.556Z"),
    "__v" : 0
}

我正在使用节点 v11.7.0、mongo v3.6.3 和 mongoose ^5.4.0 请帮帮我,这将很有帮助。谢谢你。

标签: node.jsmongodbmongoose

解决方案


创建房间时,您从未明确设置 ownerId 字段,并且它没有默认值。因此,ownerId 未存储在数据库中,因为该值未定义...

您的房间创建应如下所示:

const room = new Room({  
  room_name: req.body.roomname,
  ownerId: user._id,
  password: " "
});

推荐阅读