【发布时间】:2019-03-29 11:36:34
【问题描述】:
我在 mongodb 上有一个用户集合和一个投资组合集合。投资组合模型引用用户集合的 objectid。我正在尝试这样做,因此当用户登录并尝试添加他们已有的文档时,路由器会阻止它。现在所有这一切都是查看投资组合集合中的所有文档,但我试图先按用户过滤它,然后搜索名称以查看它是否存在。
portfolio.find({name: req.body.name})
.count()
.then(count => {
if (count > 0) {
// There is an existing user with the same username
res.status(400).json({message: 'Stock already saved!'});
}else{
portfolio
.create({
user: req.body.user,
name: req.body.name,
description: req.body.description,
symbol: req.body.symbol,
image: req.body.image,
})
.then(portfolioPost => res.status(201).json(portfolioPost.serialize()))
.catch(err => {
// console.error(err);
res.status(500).json({ error: 'Something went wrong' });
});
}
})
这是模型
const listSchema = mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: "Users" },
name: { type: String, required: true },
description: {type:String, required: true},
image: {type:String},
symbol: {type: String, required: true}
});
【问题讨论】:
-
从您的问题中不清楚您想问什么 - 查看代码或解决您遇到的错误或上述代码不起作用的原因?
标签: node.js mongodb express mongoose mongoose-schema