【发布时间】:2019-08-18 12:59:21
【问题描述】:
所以我有这个猫鼬模式:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CommentSchema = new Schema({
body: {type: String, required: true, max: 2000},
created: { type: Date, default: Date.now },
flags: {type: Number, default: 0},
lastFlag: {type: Date, default: Date.now()},
imageBanned: {type: Boolean, default: false},
fileName: {type: String, default: ""}
}, {
writeConcern: {
w: 0,
j: false,
wtimeout: 200
}
});
var PostSchema = new Schema({
body: {type: String, required: true, max: 2000},
created: { type: Date, default: Date.now },
flags: {type: Number, default: 0},
lastFlag: {type: Date, default: Date.now()},
fileName: {type: String, default: ""},
imageBanned: {type: Boolean, default: false},
board: {type: String, default: ""},
comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]
}, {
writeConcern: {
w: 0,
j: false,
wtimeout: 200
}
});
var Post = mongoose.model('Post', PostSchema);
var Comment = mongoose.model('Comment', CommentSchema)
module.exports = {Post, Comment}
我正在尝试在 post 的评论数组中查询评论。
这是我正在尝试的端点:
router.post('/flagComment', (req, res, next)=>{
console.log('inside /flagComment')
console.log('value of req.body: ', req.body)
model.Post.findOne({"comments._id": req.body.id}).exec((err, doc)=>{
if(err){
console.log('there was an error: ', err)
}
console.log('the value of the found doc: ', doc)
res.json({dummy: 'dummy'})
})
})
但是,这会给出以下终端输出:
value of req.body: { id: '5c9bd902bda8d371d5c808dc' }
the value of the found doc: null
这不正确...我已验证 ID 正确 - 为什么找不到评论文档?
编辑:
我尝试了这个解决方案 (Can't find documents searching by ObjectId using Mongoose),方法是这样设置 objectID:
var ObjectId = require('mongoose').Types.ObjectId;
router.post('/flagComment', (req, res, next)=>{
console.log('inside /flagComment')
console.log('value of req.body: ', req.body)
console.log('value of objid req id : ', ObjectId(req.body.id))
model.Post.find({"comments._id": ObjectId(req.body.id)}).exec((err, doc)=>{
if(err){
console.log('there was an error: ', err)
}
console.log('the value of the found doc: ', doc)
res.json({dummy: 'dummy'})
})
})
我得到以下终端输出:
value of req.body: { id: '5c9bd902bda8d371d5c808dc' }
value of objid req id : 5c9bd902bda8d371d5c808dc
the value of the found doc: []
所以,这还不是一个解决方案,尽管它似乎比我的更好。
【问题讨论】:
标签: javascript node.js database mongodb mongoose