【发布时间】:2020-10-29 13:08:28
【问题描述】:
我在控制台上收到错误消息:无法读取 null 的属性“喜欢” 我正在使用邮递员来获取请求并做出响应和响应。 数组 'likes' 是空的,在这里我试图在其中插入用户 ID,但无法通过 unshift() 方法插入。
这是在 Posts.js 文件中定义的架构
const { text } = require('express');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PostSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
text: {
type: String,
required: true
},
name: {
type: String
},
avatar: {
type: String
},
likes: [
{
users: {
type: Schema.Types.ObjectId,
ref: 'users'
}
}
],
comment: [
{
users: {
type: Schema.Types.ObjectId,
ref: 'users'
},
text: {
type: String,
required: true
},
name: {
type: String,
},
avatar: {
type: String
},
date: {
type: Date,
default: Date.now
}
}
],
date: {
type: Date,
default: Date.now
}
});
module.exports = Post = mongoose.model('post', PostSchema);
这是将请求放入文件 posts.js 的快速代码
const express = require('express');
const router = express.Router();
const { check, validationResult } = require('express-validator/check');
const auth = require('../../middleware/auth');
const Posts = require('../../models/Posts');
const User = require('../../models/User');
const { route } = require('./profile');
router.put('/like/:id', auth, async(req, res) => {
try {
const post = await Post.findById(req.params.id);
// Check if the post has already been liked
if(post.likes.filter(like => like.user.toString() === req.user.id).length > 0) {
return res.status(400).json({ msg: 'Post already liked' });
}
post.likes.unshift({ user: req.user.id });
await post.save();
res.json(post.likes);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
【问题讨论】:
-
据我所知,我假设
const post = await Post.findById(req.params.id);返回 null。您很可能没有指定 ID 的记录。 -
@GytisTG 是的,我明白了你的意思,但即使在输入正确的记录后,用户 ID 也不包含在“喜欢”数组中。你知道为什么会这样吗?
-
你在 posts.js 中调用了你的模型
Posts,但你在等待Post。 -
@expressjs123 我创建了一个 Post by post 的实例,顺便感谢您的帮助,我已经解决了问题,实际上是定义的架构中的拼写错误,我错误地在应该写的地方写了“用户”成为“用户”。
-
@Gytis TG 我已经用 cmets 发布了答案,我在两行上犯了错字。
标签: node.js mongodb express mongoose