You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose一对多关联保存异常:评论未仅存ID而存为嵌入文档

Mongoose关联存储问题:让博客仅保存评论的ObjectId而非嵌入文档

我看了你现在的代码,问题出在你直接把未保存的Comment实例推到了博客的comments数组里——Mongoose这时候会默认把它当成嵌入文档处理,而不是存储关联的ObjectId。咱们来改改代码:

先回顾你的模型定义(方便对照)

Post模型

var mongoose = require('mongoose'), Schema = mongoose.Schema 
var blogScheam = Schema({ 
  title: String, 
  comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }] 
}); 
module.exports = mongoose.model('Post', blogScheam);

Comment模型

var mongoose = require('mongoose'), Schema = mongoose.Schema 
var commentSchema = Schema({ 
  comment: String, 
  user: { type: Schema.Types.ObjectId, ref: 'User' } 
}); 
module.exports = mongoose.model('Comment', commentSchema);

User模型

var mongoose = require('mongoose'), Schema = mongoose.Schema 
var userScheam = Schema({ 
  name: String, 
  age: Number, 
  posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }] 
}); 
module.exports = mongoose.model('User', userScheam);

修改后的接口函数

你需要先把评论保存到数据库,拿到它的_id之后,再把这个ID添加到博客的comments数组里,而不是直接推未保存的实例。代码如下:

app.post('/comment', async (req, res) => { 
  try {
    // 1. 先找到对应的博客
    const blog = await Blog.findById(req.body._id);
    if (!blog) {
      return res.render("details"); // 处理博客不存在的情况
    }

    // 2. 创建并保存评论到数据库
    const comment = new Comment({ comment: req.body.title });
    await comment.save(); // 这里先保存评论,拿到它的_id

    // 3. 把评论的_id添加到博客的comments数组
    blog.comments.push(comment._id);
    await blog.save();

    res.render("details");
  } catch (err) {
    console.error(err); // 打印错误方便调试
    res.render("details");
  }
});

为什么之前会变成嵌入文档?

当你直接把一个未保存的Mongoose文档实例(比如你创建的comment)推到关联数组里时,Mongoose会自动把它作为嵌入子文档存储,而不是存储它的ObjectId。只有当你传入一个已经保存的文档的_id,或者是一个合法的ObjectId字符串/对象时,Mongoose才会按照你定义的ref关联规则,只存储ID值。

另外我注意到你代码里写了comment2,应该是笔误,改成comment就好啦~

内容的提问来源于stack exchange,提问作者saytri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:43:11