当用户单击按钮时,我会尝试在添加之前查看该用户是否已存在于数组中,否则我不想将其添加到现有数组中。
这是猫鼬模式
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”必须是一个对象
这向你展示了一个错误,因为请求是一个对象数组。并且您正在查询以userId
在数组中找到。您应该告诉 mongo 与对象数组中的哪个属性匹配。
改成这样
Product.find( { "requests.userId" : userId })
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句