1

Mongoose 为 DB 中的第一个对象 _ID 0 返回 null,即使它存在。我可以使用类似的代码很好地检索第一篇文章,但我无法检索第一个标签。我可以检索我的所有数据,但第一个标签(第一个帖子的 tag1 除外)。如果我添加带有标签的第二个帖子:tag4、tag5 和 tag6,我可以检索第二个帖子的所有数据,包括 tag4。如果我在稍后的帖子中指向 tag1,则无法检索它。

我做了一些搜索,知道返回 null 意味着找不到记录。除了 findById 之外,我还尝试使用 find 和 findOne 并获得相同的结果。如果记录存在,我无法弄清楚我哪里出错了。我确信可能有更好的方法来做到这一点。

谢谢您的帮助。

我正在使用 mongoose、mongoose-simpledb 和 tungus 和 node-webkit。

保存标签:

$.each(tagArray, function(i, t) {
    var tags = db.Tags();
    tags.nextCount(function(err, count) {
        post.tags.push(count + i); //tag ID to post
    });
    tags.text= tagArray[i]; //tag text
    post.nextCount(function(err, count) {
        tags.posts.push(count); //post ID to tag
    });
    tags.save(function(err) {
        if (err) {throw err;}
        console.log('tag saved');
    });
});

查找标签:

$.each(results[i].tags, function(j, t) {
    db.Tags.findById(results[i].tags[j], function(err, tag) {
        if (err) {return console.error(err);}
        if (!tag) {return console.log('Could not find tag...');}
        postContent += '<a href="">' + tag.text + '</a> ';
    });
});

或者,如果我使用以下 tag2 而不是应该返回的 tag1 ,则返回。

db.Posts.
    find({}).
    populate('tags').
    exec(function(error, post) {
        console.log(post[0].tags[0].text);
    });

标签 模型

var ObjectId = require('mongoose-simpledb').Types.ObjectId;

exports.schema = {
    _id: Number,
    text: String,
    posts: [{type: ObjectId, ref: 'Posts', index: true}]
};

标签数据库

{"k":"0000000078","o":"0000000061","v":"001"}
{"_id":0,"_uid":1,"_dt":1409869458919,"_s":"c245621efdb176d3f4dd2db749590730"}
{"_id":0,"text":"Tag1","posts":[{"$wrap":"$oid","v":0}],"__v":0}
{"k":"0000000078","o":"0000000061","v":"001"}
{"_id":1,"_uid":1,"_dt":1409869458921,"_s":"80bc4453ee777de0177b27ba76ddc859"}
{"_id":1,"text":"Tag2","posts":[{"$wrap":"$oid","v":0}],"__v":0}
{"k":"0000000078","o":"0000000061","v":"001"}
{"_id":2,"_uid":1,"_dt":1409869458930,"_s":"12682b1c27ea57e8c09b87a2a6605510"}
{"_id":2,"text":"Tag3","posts":[{"$wrap":"$oid","v":0}],"__v":0}

使用标签数据库上的查找:

db.Tags.findOne({
    _id: '0'
}, function(err, result) {
    if (err) return console.error(err);
    console.dir('findOne: ' +result.text);
    //throws error - Cannot read property 'text' of null
});

db.Tags.
findById(0, function(err, tag) {
    if (err) return console.error(err);
    console.log('tag by id: ' + tag);
    //returns - null
});

db.Tags.
find({}).
exec(function(error, tag) {
    console.log("find:" + tag[0]);
    //returns - ( _id: 0, text: 'Tag1', _v: 0, posts: [0] )
    //correctly finding the tag but not by id
});

如果我更改这些查找函数以查找除第一个标记之外的任何标记,则会返回正确的信息。

4

1 回答 1

0

这个问题原来是 mongoose-simpledb。我不确定问题是 mongoose-simpledb 中的错误还是与 tungus 的冲突,但是一旦删除 mongoose-simpledb,“相同”的代码就可以正常工作。

于 2014-09-11T01:34:48.700 回答