javascript - 为什么填充值数组后变成空?

标签 javascript node.js mongodb

我想在我的帖子中填充答案(评论)。但在填充时它会变为空,而在此之前它会存储答案 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});
    }
});

最佳答案

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

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 }

也许这有助于查找错误

关于javascript - 为什么填充值数组后变成空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55324367/

相关文章:

javascript - 单击按钮时如何添加表格行 : jquery

javascript - 如何修复 'TypeError: Cannot read property ' keycloak-token' of undefined' javascript 中的错误?

node.js - 我可以使用卡片在团队中显示多个按钮/选项吗?

css - 在 Express 元素中本地包含 Bootstrap/Semantic UI?

node.js - 如果 MongoDB 中已存在索引,则忽略 Mongoose 模式中的过期设置

mongodb - 查询mongodb中嵌入文档的数组

javascript - 简单 meteor (1.7.0.5) 发布/订阅集合不起作用

javascript - Jest 模拟不适用于 React 测试库

javascript - Jquery - 更改背景图像 - 抛出奇怪的错误

python - Mongodb 我可以构造这些数据吗