gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:33:19 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com