为什么在填充值数组后变为空?

时间:2019-03-24 13:36:40

标签: javascript node.js mongodb

我想在我的帖子中填写答案(评论)。但是在填充之前,它变为null,而在此之前它存储了存储答案的ID的功能。

我的帖子架构

var doubtsSchema = new mongoose.Schema({
    title : String,
    content : String,
    tags : String,
    created : {
        type : Date,
        default : Date.now},
    author : {
        id : {
            type : mongoose.Schema.Types.ObjectId, 
            ref : "User"},
        username : String},
    answers : [{
        type : mongoose.Schema.Types.ObjectId,
        ref : "Answers"}]});

module.exports = mongoose.model("Doubts",doubtsSchema);

我的回答模式

var answersSchema = new mongoose.Schema({
    content : String,
    created : {
        type : Date,
        default : Date.now},
    author : {
        id : {
            type : mongoose .Schema .Types . ObjectId, 
            ref  : "User"},
        username : String},
    likes_count : Number});


module.exports = mongoose.model("Answers",answersSchema);

人群无法正常工作

Doubts.findById(req.params.id).populate('answers').exec(function(err,foundDoubt) {
    if(err) {
        console.log(err);
    } else {
        console.log("here");
        console.log(foundDoubt);
        res.render("doubts/show",{doubt : foundDoubt});
    }
});

1 个答案:

答案 0 :(得分:0)

我举了一个简单的例子,它有效

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/test", {useNewUrlParser: true});

const UserSchema = new mongoose.Schema({
    name: String,
    comments: [{type: mongoose.Schema.Types.ObjectId, ref: "Comments"}]
});

const CommentSchema = new mongoose.Schema({
    content: ""
});

const Users = mongoose.model("Users", UserSchema);
const Comments = mongoose.model("Comments", CommentSchema);

// Adding data
Promise.all([
    new Comments({content: "test 1"}).save(),
    new Comments({content: "test 2"}).save(),
    new Comments({content: "test 3"}).save()
]).then(result => {
    result = result.map(r => r._id);
    new Users({name: "test", comments: result}).save().then(user => {
        // Getting with populate
        Users.findById(user._id).populate("comments").then(console.log);
    })
}).catch(console.error);

在控制台中:

{ comments:
   [ { _id: 5c979d9dedc0b1db90fe81dd, content: 'test 1', __v: 0 },
     { _id: 5c979d9dedc0b1db90fe81de, content: 'test 2', __v: 0 },
     { _id: 5c979d9dedc0b1db90fe81df, content: 'test 3', __v: 0 } ],
  _id: 5c979d9dedc0b1db90fe81e0,
  name: 'test',
  __v: 0 }

也许会有助于发现错误