我有两个模式,
// Post.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const postSchema = new Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "user"
},
likes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "postLike"
}
],
date: {
type: Date,
default: Date.now
}
});
module.exports = Post = mongoose.model("post", postSchema);
和
//PostLike.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const postLikeSchema = new Schema({
post: {
type: mongoose.Schema.Types.ObjectId,
ref: "post"
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "user"
},
// Flag to denote like or dislike
likeOrDislike: {
type: Boolean,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = PostLike = mongoose.model("postLike", postLikeSchema);
我对帖子进行投票时,它会像这样将其保存在PostLike
中:
但是当我尝试检索帖子时
let post = await Post.find({ _id: id }).populate("likes");
console.log(post);
return res.json(post);
它返回长度为0的点赞数组,
[ likes: [],
date: 2019-09-03T07:03:02.481Z,
user: 5d495163bd47260574dff2c4,
__v: 0 } ]
不确定从这里要去哪里。我尝试用.populate("postLike");
填充,但这也不起作用。在保存喜欢或不喜欢的方法中,我还必须执行Post.findOneAndUpdate(...)
吗?因为这样做消除了在架构中包含引用的全部问题。