当用户单击按钮时,我试图在添加该用户之前先查看该用户是否已存在于数组中,否则我不想将其添加到现有数组中。
这是猫鼬模式
const Schema = mongoose.Schema;
const productSchema = new Schema({
title: {
type: String,
required: true
},
category: {
type: String,
required: true
},
image: {
type: String,
required: true
},
description: {
type: String,
required: true
},
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
createdAt: {
type: Date,
default: Date.now
},
requests: [
{
userId: {type: Schema.Types.ObjectId, required: true},
firstName: {type: String},
}
],
});
module.exports = mongoose.model('Product', productSchema);
和查询
exports.postRequest = (req, res, next) => {
const productId = req.body.productId;
const userId = req.body.userId;
const firstName = req.body.firstName;
Product.find({requests: userId})
.then(product => {
console.log(product);
})
.catch(err => {
console.log(err);
});
};
我认为这就是检查数组中是否存在值的全部操作,但出现错误:
ObjectParameterError:Document()的参数“ obj”必须是一个对象
答案 0 :(得分:1)
这表明u错误,因为请求是对象数组。您正在查询以找到数组中的end_list
。您应该告诉mongo对象数组中要匹配的属性。
以这种方式更改
userId