我有一个mongoose函数,我试图在我的User对象中创建一个对象,在我的Listing对象中创建另一个对象。我已经尝试过保存两次,但是收到错误而只保存了第一个错误。我怎么能这样做?
下面的架构。
var userSchema = new Schema({
created: { type: Date },
email: { type: String, unique: true, lowercase: true },
password: { type: String, select: false },
listings: [Listing.schema],
myBids: [Bids.schema]
});
var ListingSchema = new Schema({
topic: String,
uid: String,
bids: [Bid.schema]
})
var BidSchema = new Schema({
uid: String,
respondEmail: String,
response: String,
});
我的创建功能。在列表中创建Bid对象。我现在想在当前用户中创建一个重复的Bid对象。
function create(req, res) {
db.Listing.findById(req.params.listingId, function(err, foundListing) {
if (err) {
console.log('Error:', err);
}
db.User.findOne({
'listings._id': req.params.listingId
}, function(err, foundUser) {
for (let i = 0; i < foundUser.listings.length; i++) {
if (foundUser.listings[i]._id == req.params.listingId) {
db.User.findById(req.user, function(err, currentUser) {
var newBid = new db.Bid(req.body);
// trying to push here
// currentUser.myBid.push(newBid);
// currentUser.save();
var oldLength = foundUser.listings[i].bids.length;
foundUser.listings[i].bids.set(oldLength, newBid);
foundUser.save(function(err, savedListing) {
if (err) {
console.log('Error: ', err);
return;
}
res.json(newBid);
});
})
}
}
})
});
};