所以基本上我有一个愿望清单,我想要使用放置请求(我使用postman btw)在愿望清单产品数组中添加一堆产品。 这是愿望清单架构,是的,我知道数据库中的文件名是" whishlist" ....我讨厌错别字
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var whishList = new Schema({
title: {type: String, default: "Cool whishlist"},
products:[{type: ObjectId, ref:'Product'}]
});
module.exports = mongoose.model('WhishList', whishList);
这是产品架构
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var product = new Schema({
title: String,
price: Number,
likes: {type: Number, default: 0}
});
module.exports = mongoose.model('Product', product);
现在这是我正在尝试运行的代码
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/swag-shop');
var Product = require('./model/product');
var wishList = require('./model/wishlist');
app.put('/wishlist/product/add', function(request, response){
Product.find({_id: request.body.productId}, function(err, product){
if(err) {
response.status(500).send({err: "could not add item to wishlist"});
}else{
wishList.update({_id: request.body.wishlistId},{$addToSet: {products: product._id}}, function(err, wishlist){
if(err){
response.status(500).send({err: "could not add item to wishlist /update/"});
}else{
response.send(wishlist);
}
});
}
});
我真的无法看到问题出在哪里我尝试删除文档并再次发布,但我遇到了同样的问题。 提前致谢
答案 0 :(得分:4)
问题是Product.find()
的结果是Mongoose文档数组,如果查询匹配集合中的任何文档而不是您想要的单个文档。
因此,{$addToSet: {products: product._id}}
表达式解析为{$addToSet: {products: undefined}}
,因为product
是一个数组,product._id
未定义。举个这个简单的例子
var product = [{ '_id': 1 }];
console.log(product._id) // logs undefined
要解决此问题,您可以访问数组中唯一的元素
wishList.update(
{ '_id': request.body.wishlistId },
{ '$addToSet': { 'products': product[0]._id} },
function(err, wishlist) { ... }
);
或者使用findOne()
方法在查询产品时返回单个文档:
Product.findOne({ '_id': request.body.productId }, function(err, product) {
if(err) {
response.status(500).send({err: "could not add item to wishlist"});
} else {
wishList.update(
{ '_id': request.body.wishlistId },
{ '$addToSet': { 'products': product._id } },
function(err, wishlist) { ... }
);
}
});
findById()
方法在这种情况下也很有用,例如
Product.findById(request.body.productId, function(err, product) {
if(err) {
response.status(500).send({err: "could not add item to wishlist"});
} else {
wishList.update(
{ '_id': request.body.wishlistId },
{ '$addToSet': { 'products': product._id } },
function(err, wishlist) { ... }
);
}
});