$addToSet 到一个数组,但它给了我 null [英] $addToSet to an array but it gives me null

查看:34
本文介绍了$addToSet 到一个数组,但它给了我 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我有一个愿望清单,我有一堆产品要使用放置请求添加到愿望清单产品数组中(顺便说一句,我正在使用邮递员).这是愿望清单模式,是的,我知道数据库中的文档名称是愿望清单"....我讨厌拼写错误

so basically I've a wish list and I've bunch of products that I want to add inside the the wish list products array using a put request (I'm using postman btw). This is the wish list schema, and yes I know that the document's name in the db is "whishlist"....I hate typos

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);

现在这是我要运行的代码

and now this is the code that I am trying to run

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);
                    }
                });
            }
        });

我真的不知道问题出在哪里我尝试删除文档并再次发布,但我遇到了同样的问题.提前致谢

I really can't see where is the problem I tried deleting the document and posting it again but I had the same problem. Thanks in advance

推荐答案

问题是 Product.find() 的结果是一个 Mongoose 文档数组,如果查询匹配集合而不是您想要的单个文档.

The issue is that the result from Product.find() is an array of Mongoose documents if the query matches any documents in the collection instead of a single document which you want.

因此表达式 {$addToSet: {products: product._id}} 解析为 {$addToSet: {products: undefined}} 因为 product 是一个数组,product._id 是未定义的.举个简单的例子

Thus the expression {$addToSet: {products: product._id}} resolves to {$addToSet: {products: undefined}} because product is an array and product._id is undefined. Take this simple example

var product = [{ '_id': 1 }];
console.log(product._id) // logs undefined

<小时>

为了解决这个问题,你可以访问数组中唯一的元素


To remedy this problem, you can either access the only element in the array as

wishList.update(
    { '_id': request.body.wishlistId },
    { '$addToSet': { 'products': product[0]._id} }, 
    function(err, wishlist) { ... }
);

或者使用 findOne() 方法,该方法在查询产品时返回单个文档:

Or use the findOne() method which returns a single document when querying the product:

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() 方法在这种情况下也很有用,即

The findById() method is also useful in this case i.e.

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) { ... }
        );
    }
});

这篇关于$addToSet 到一个数组,但它给了我 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆