如何用Mongoose向嵌套文档添加元素?旧代码报错求新语法
问题解答
错误原因
你碰到的TypeError: Cannot read properties of undefined (reading 'push')错误,核心是字段名拼写错误,和Mongoose版本更新无关。你的Post模型Schema里定义的评论字段是comments(复数形式),但代码里调用的是aPost.comment(单数),这个属性不存在,自然无法调用push方法。
修正后的代码
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); const Schema = mongoose.Schema; const commentSchema = new Schema({ text: String, username: String, }); const postSchema = new Schema({ text: String, username: String, comments: [commentSchema], // 字段为复数comments }); const PostModel = mongoose.model('post_coll', postSchema); const CommentModel = mongoose.model('comment_coll', commentSchema); const aPost = new PostModel({ text: 'one', username: 'two', }); // 修正:将comment改为comments aPost.comments.push({ text: 'one', username: 'two', }); aPost.save((err, res) => {});
额外优化建议
如果你的Mongoose版本是v6及以上,推荐使用async/await替代回调函数,代码可读性更强:
async function savePostWithComment() { try { await mongoose.connect('mongodb://localhost/test'); const aPost = new PostModel({ text: 'one', username: 'two', }); aPost.comments.push({ text: 'one', username: 'two', }); const savedPost = await aPost.save(); console.log(savedPost); } catch (err) { console.error(err); } finally { await mongoose.disconnect(); } } savePostWithComment();
内容的提问来源于stack exchange,提问作者Sandra Schlichting
相关产品推荐
相关产品推荐

