Javascript 使用mongoose方法在架构中插入数据
我有一个订单模式,它有两个字段,一个是userid,另一个是username。我从API接收userid我想要的是基于userid我从用户模式中检索用户名并在order模式中更新它。为此,我在order模式中添加了一个方法Javascript 使用mongoose方法在架构中插入数据,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我有一个订单模式,它有两个字段,一个是userid,另一个是username。我从API接收userid我想要的是基于userid我从用户模式中检索用户名并在order模式中更新它。为此,我在order模式中添加了一个方法 OrderSchema.methods.setCustomerName=function() { let _id=this.userID; User.findOne({_id},(err,item) => { if(item)
OrderSchema.methods.setCustomerName=function()
{
let _id=this.userID;
User.findOne({_id},(err,item) =>
{
if(item)
{
this.customer=item.firstName+" "+item.lastName;
}
})
}
我在创建订单时调用了这个方法
const newOrder = Order({
products: products,
price: totalAmount,
totalAmount: totalAmount,
userID: userID
})
newOrder.setCustomerName();
最后,保存新订单
newOrder.save((err, order) => {
if (order) {
return res.json({
status: true,
message: "Payment received"
})
}
})
然而,这是行不通的。我甚至没有在用户名字段中得到一个空值。请说明我做错了什么。试试:
const newOrder = new Order({
products: products,
price: totalAmount,
totalAmount: totalAmount,
userID: userID
})
建议:如果使用Async/Await而不是回调,可能会更干净